Skip to content Skip to sidebar Skip to footer

Extract Values By Key From A Nested Dictionary

Given this nested dictionary, how could I print all the 'phone' values using a for loop? people = { 'Alice': { 'phone': '2341', 'addr': '87 Eastlake Court'

Solution 1:

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

Solution 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') forvalin people.values()]
['4563', '9102', '2341']

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

Post a Comment for "Extract Values By Key From A Nested Dictionary"