简体   繁体   中英

Iterating through a nested dictionary

I have a nested dictionary with people ids and information about the age. I need to iterate through the nested dictionary in order to add a key "Adult" if the age is higher than 18. How can I assess the different id of people to use a loop and a conditional statement?

Edit: Understood how to do it thank you to the community!

You may refer to the inner dictionaries using.values(), this way, you do not need to know the explicit people ids.

for value in People.values():
    if value['Age'] > 18:
        value['Adult'] = "Yes"
    else:
        value['Adult'] = "No"

print(People)

Looping through dict in python work like this:

dict = {'A123' : {'Student_Name' : 'Lisa'} }
# Access ID with for and subcategory using this id
for id in dict:
   name = dict[id]['Student_Name']

# Assigning new value :
value = 3
for id in dict:
   dict[id]['CGPA'] = value

I'll do it that way

def treat_dict(input):
    for id in input:
        if input[id]['CGPA'] >= 3.7:
            input[id]['Honors'] = 'Yes' # Add new value
        else:
            input[id]['Honors'] = 'No'  # Add new value
    return input

In a more compressed way:

def treat_dict(input):
    for id in input:
        input[id]['Honors'] = 'Yes' if input[id]['CGPA'] >= 3.7 else 'No'
    return input

Edit: didn't see that someone replied but letting it...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM