Extract values by key from a nested dictionary

前端 未结 3 654
广开言路
广开言路 2021-01-13 19:38

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

people = {
    \'Alice\': {
        \'phone\': \'2341\',
        \         


        
相关标签:
3条回答
  • 2021-01-13 20:15

    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']
    
    0 讨论(0)
  • 2021-01-13 20:26

    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']
    
    0 讨论(0)
  • 2021-01-13 20:31
    for d in people.values():
        print d['phone']
    
    0 讨论(0)
提交回复
热议问题