Home > Back-end >  Iterating through a nested dictionary with loop and conditional statement
Iterating through a nested dictionary with loop and conditional statement

Time:02-03

I have the following nested dictionary:

Student_dict = {'A123':
{'Student_Name': 'Lisa Simpson',
'Class_Year': 1,
'CGPA': 3.98},
'A125':
{'Student_Name': 'Bart Simpson',
'Class_Year': 3,
'CGPA': 2.51},
'A234': {'Student_Name': 'Milhouse Houten',
'Class_Year': 3,
'CGPA': 3.62}}

And I have to add the key "Honors" within each of the dictionaries and associate the value "Yes" if the CGPA value of the student is higher than 3.7 and "No" otherwise, using loops and if statement.

The expected output is the following:

Student_dict = {
'A123': {
'Student_Name': 'Lisa Simpson',
'Class_Year': 1,
'CGPA': 3.98,
'Honors': 'Yes'
},
'A125': {
'Student_Name': 'Bart Simpson',
'Class_Year': 3,
'CGPA': 2.51,
'Honors': 'No'
},
'A234': {
'Student_Name': 'Milhouse Houten',
'Class_Year': 3,
'CGPA': 3.62,
'Honors': 'No'}}

I've tried various things, but my problem is assessing the different student ids (A123, A125, A234) to create my loop.

Could someone help me please?

Thank you in advance!

CodePudding user response:

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

for value in Student_dictPeople.values():
    if value['CGPA']value['Age'] > 3.7018:
        value['Honors']value['Adult'] = "Yes"
    else:
        value['Honors']value['Adult'] = "No"

print(Student_dict)

Output:

{'A123': {'Student_Name': 'Lisa Simpson', 'Class_Year': 1, 'CGPA': 3.98, 'Honors': 'Yes'}, 'A125': {'Student_Name': 'Bart Simpson', 'Class_Year': 3, 'CGPA': 2.51, 'Honors': 'No'}, 'A234': {'Student_Name': 'Milhouse Houten', 'Class_Year': 3, 'CGPA': 3.62, 'Honors': 'No'}}

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