wilberox
wilberox

Reputation: 193

Accesssing all values from same key for different dictionaries within nested dictionary

I have a nested dictionary:

d = { 'wing': {'name': 'Ali', 'age': '19'}, 
    'scrumHalf': {'name': 'Bob', 'age': '25'},
    'flyHalf': {'name': 'Sam', 'age': '43'},
    'prop': {'name': 'rob', 'age': '33'}}

I want to pull out the values for age only to generate a list [19, 25, 43, 33]

I want to do this using a for loop, and as naively as possible, as I usually find that easiest to understand.

I have managed to print all of the keys using a for loop:

for i in d:
    print i
    for j in d[i]:
        print j

but when I tried to edit it to print the values I got the error NameError: name 'value' is not defined. How can I get 'value' to mean the value attached to a key?

Here is my edited version

for i in d:
    print (i[value])
    for j in d[i]:
        print (j[value])

I am using python 2.7

Upvotes: 0

Views: 56

Answers (2)

Mykola Zotko
Mykola Zotko

Reputation: 17911

You can access values in the dict with the help of the method values():

[i['age'] for i in d.values()]
# ['19', '25', '43', '33']

Upvotes: 1

Vishnudev Krishnadas
Vishnudev Krishnadas

Reputation: 10970

>>> [d.get(k).get('age') for k, v in d.items()]
['33', '25', '19', '43']

In-order to access a dictionary's value you are iterating through keys first which is correct i.e. for i in d:. So, in order to access value of key i in d, you'll need to do d[i] which will give you the value, for example {'name': 'rob', 'age': '33'} then to access the required key you'll have to access from dictionary once more i.e. d[i]['age'].

Upvotes: 0

Related Questions