[英]Extract values by key from a nested dictionary
Given this nested dictionary, how could I print all the "phone" values using a for loop?鉴于这个嵌套字典,我如何使用 for 循环打印所有“电话”值?
people = {
'Alice': {
'phone': '2341',
'addr': '87 Eastlake Court'
},
'Beth': {
'phone': '9102',
'addr': '563 Hartford Drive'
},
'Randy': {
'phone': '4563',
'addr': '93 SW 43rd'
}
for d in people.values():
print d['phone']
Using a list comprehension 使用列表理解
>>> [people[i]['phone'] for i in people]
['9102', '2341', '4563']
Or if you'd like to use a for
loop. 或者,如果您想使用for
循环。
l = []
for person in people:
l.append(people[person]['phone'])
>>> l
['9102', '2341', '4563']
Loop over the values and then use get()
method, if you want to handle the missing keys, or a simple indexing to access the nested values. 循环遍历值,然后使用get()
方法(如果要处理丢失的键),或者使用简单的索引访问嵌套的值。 Also, for the sake of optimization you can do the whole process in a list comprehension : 另外,为了优化起见,您可以通过列表理解来完成整个过程:
>>> [val.get('phone') for val in people.values()]
['4563', '9102', '2341']
Readable code is more valuable than optimized code.可读代码比优化代码更有价值。 If the time for the operation to complete doesn't matter.如果操作完成的时间无关紧要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.