Extract values by key from a nested dictionary

天涯浪子 提交于 2020-01-11 06:59:52

问题


Given this nested dictionary, how could I print all the "phone" values using a for loop?

people = {
    'Alice': {
        'phone': '2341',
        'addr': '87 Eastlake Court'
        },

    'Beth': {
        'phone': '9102',
        'addr': '563 Hartford Drive'
        },

    'Randy': {
        'phone': '4563',
        'addr': '93 SW 43rd'
        }

回答1:


for d in people.values():
    print d['phone']



回答2:


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. 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']



回答3:


Using a list comprehension

>>> [people[i]['phone'] for i in people]
['9102', '2341', '4563']

Or if you'd like to use a for loop.

l = []
for person in people:
    l.append(people[person]['phone'])

>>> l
['9102', '2341', '4563']


来源:https://stackoverflow.com/questions/26306448/extract-values-by-key-from-a-nested-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!