Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading