Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
        },

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

    'Randy': {
        'phone': '4563',
        'addr': '93 SW 43rd'
        }
like image 512
Stephen Knight Avatar asked Oct 10 '14 19:10

Stephen Knight


3 Answers

for d in people.values():
    print d['phone']
like image 190
jacg Avatar answered Oct 16 '22 12:10

jacg


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']
like image 29
Mazdak Avatar answered Oct 16 '22 11:10

Mazdak


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']
like image 2
Cory Kramer Avatar answered Oct 16 '22 11:10

Cory Kramer