Python for loop through nested dictionary question?


Trying to loop through a nested dictionary and want to store values into name, age and occupation. Without manually creating those variables within the for loop. Is this even possible? Just trying to create cleaner looking code. Thank you.

people = {
    1: {"name": "Simon", "age": 20, "occupation": "Data scientist"},
    2: {"name": "Kate", "age": 30, "occupation": "Software engineer"},
    3: {"name": "George", "age": 22, "occupation": "Manager"},

for person in people:
    for name, age, occupation in people[person].values():
        print(name, age, occupation)

>Solution :

Inner loop is not necessary. You just need to unpack the values object.

for person in people.values():
    name, age, occupation = person.values()
    print(name, age, occupation)

Leave a ReplyCancel reply