Python for loop through nested dictionary question?

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)
Asked By: RishV

||

Answers:

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)
Answered By: matszwecja

try this

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 index, person in people.items():
    name, age, occupation = person.values()
    print(name, age, occupation)

If you want index you can keep it and if you don’t you can change it to underline

Answered By: chrisfang

try this

   for person in people:
    name, age, occupation = people[person].values()
    print(name, age, occupation)
Answered By: Navaras P
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.