-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
  • 34,189
  • 11
  • 57
  • 87
Victor
  • 509
  • 2
  • 5
  • 18

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
  • 4,849
  • 3
  • 23
  • 38
-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
  • 11,076
  • 8
  • 58
  • 102