-3

I have a dictionary which has the following structure in a python program {'John':{'age': '12', 'height':'152', 'weight':'45}}, this is the result returned from a function.

My question is how may I extract the sub-dictionary please? so that I can have the data in this form only {'age': '12', 'height':'152', 'weight':'45}.

*I can think of a solution of using for loop to go through the dictionary, since there is only one item in this dictionary, I can then store it into a new variable, but I could like to learn an alternative please

Many thanks

Hai Vu
  • 37,849
  • 11
  • 66
  • 93
Victor
  • 659
  • 3
  • 8
  • 19

2 Answers2

2

To get a value from a dictionary, use dict[key]:

>>> d = {'John':{'age': '12', 'height':'152', 'weight':'45'}}
>>> d['John']
{'age': '12', 'height': '152', 'weight': '45'}
>>> 
rassar
  • 5,412
  • 3
  • 25
  • 41
-1
>>> d = {'John':{'age': '12', 'height':'152', 'weight':'45'}, 'Kim':{'age': '13', 'height': '113', 'weight': '30'}}
>>> for key in d:
...     print(key, d[key])
... 
John {'height': '152', 'weight': '45', 'age': '12'}
Kim {'height': '113', 'weight': '30', 'age': '13'}

Just access the subdictionary with d[key]. If you have multiple keys, something like the above loop will allow you to go through all of them.

blacksite
  • 12,086
  • 10
  • 64
  • 109