Andre
Andre

Reputation: 23

Getting a type error with a nested dictionary

I am working on a simple program and I am having this problem with my nested dictionary values returning an integer and getting a KeyError.

I have tried initializing the key as a dictionary but it still doesn't seem to work.

people = {
    1: {
        'name': 'John',
        'age': '27',
        'sex': 'Male'
    },
    2: {
       'name': 'Marie', 
       'age': '22', 
       'sex': 'Female'
    }
}

todays_names = {}

x=1

for item in people:
    home = people[x]['name']
    todays_names[x] = {}
    todays_names[x]['home'] = home
    x += 1

print(todays_names)

for item in todays_names:
    print(item['home'])


I would expect it to print John and Marie for each item but it does not. when i print the dictionary it looks like:

 {1: {'home': 'John'}, 2: {'home': 'Marie'}}

though which seems valid to me.

Upvotes: 0

Views: 167

Answers (1)

Denver
Denver

Reputation: 639

The issue is you are not properly accessing the nested dictionary. This line:

for item in todays_names:
    print(item['home'])

is throwing an error because item is the key of the outer dictionary while home is the key of the nested dictionary. Your print statement looks something like this:

# item = 1
print(1['home'])

which is throwing an error. Try something like this:

for item in todays_names:
    print(todays_items[item]['home'])

This should give you the expected output because todays_items is the dictionary, item is the key of the outer level and home is the key of the nested dictionary. This will print John and Marie.

Upvotes: 1

Related Questions