Home > front end >  Iterating through a nested dictionary
Iterating through a nested dictionary

Time:02-02

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!

CodePudding user response:

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)

CodePudding user response:

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...

  •  Tags:  
  • Related