Python 3: Unable to extract value from nested key

Viewed 327

In the process of self-learning Python. On the topic of nested dictionaries. I am unable to accomplish this example:

Extract the value associated with the key color and assign it to the variable color. Do not hard code this.

info = {'personal_data':
         {'name': 'Lauren',
          'age': 20,
          'major': 'Information Science',
          'physical_features':
             {'color': {'eye': 'blue',
                        'hair': 'brown'},
              'height': "5'8"}
         },
       'other':
         {'favorite_colors': ['purple', 'green', 'blue'],
          'interested_in': ['social media', 'intellectual property', 'copyright', 'music', 
 'books']
         }
      }

I’ve been able to extract from an un-nested dictionary, getting into the second and third layer is proving beyond my understanding. I neglected to keep every solution I attempted however this is a sample of my lines of thought.

Keyerror 'color'

c = []
for col in info:
    c.append(info[col]['color'])

Keyerror ‘color

for c in info.values():
    print(c['color'])

TypeError: string indices must be integers

print(info['personal_data']['name']['color'])

I apologize if the syntax of this post is off. I'm learning the etiquette.

2 Answers

You should extract the value associated with the key color:

color = info['personal_data']['physical_features']['color']

and, for example, you can print it:

for body_part, body_part_color in color.items():
    print(f"Body part: {body_part} and it's color: {body_part_color}")

You were almost there.

>>> print(info['personal_data']['name']['color'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers

With this line you're accessing name variable, that is a string, so when you index it with another string, the interpreter warns you with the exception TypeError: string indices must be integers.

What you want to do is:

>>> color = info['personal_data']['physical_features']['color']
>>> color
{'eye': 'blue', 'hair': 'brown'}

If you want to access a specific organ color, you need to do this:

>>> color["eye"]
'blue'
>>> color["hair"]
'brown'
Related