Jane P
Jane P

Reputation: 99

iterating over nested dictionary using for loop

I am a python newbie and learning about dictionaries. I have a list of students with their grades and I need to map each student to his grade for a specific exam.

I am using a for loop to iterate over each student name and then another loop to iterate over the exam grades. My code is below but for some reason I am not getting a desired outcome. I hoping someone can point out where I messed up. Thank you.

students = {'Student1': {'Exam1': 80, 'Exam2': 80, 'Exam3': 70},
      'Student2': {'Exam1': 90, 'Exam2': 70, 'Exam3': 65}}

student_grades = {}
for student, exam in students.items():
    student_grades = {student}
    for key,value in exam.items():
       student_grades.update({key + ':', value})

print(student_grades)


#This is what I'd like my result to look like:
({'Student1': {'Exam1': 80}}, {'Student1': {'Exam2': 80}},   {'Student1': {'Exam3': 70}}, {'Student2': {'Exam1': 90}}, {'Student2':   {'Exam2': 70}}, {'Student2': {'Exam2': 65}})

#But this is what it actually looks like:
{65, 'Student2', 90, 70, 'Exam3:', 'Exam1:', 'Exam2:'}

Upvotes: 0

Views: 989

Answers (1)

Bill M.
Bill M.

Reputation: 1548

You can use a for loop on a dictionary to iterate just through the keys. Also, it seems that what you ultimately want is a tuple filled with little dictionaries. So make student_grades a Python tuple by setting it to empty parentheses; the way you've set it to empty braces, {}, makes it an empty Python dictionary or set.

students = {'Student1': {'Exam1': 80, 'Exam2': 80, 'Exam3': 70},
      'Student2': {'Exam1': 90, 'Exam2': 70, 'Exam3': 65}}

student_grades = ()

# Loop through the students, then for each one loop through the exams
for student in students:
    for exam in students[student]:
        # Now make a new entry for student_grades, then add this entry
        new_dict = {student: {exam: students[student][exam] }}
        student_grades += (new_dict,)

print(student_grades)

Personally I prefer lists ([]) over tuples (()) in cases like this. Python can let you do for loops within elements on the fly. So here's one way to get everything in one list with a single command.

as_a_list = [ {student: {exam: students[student][exam]}} for student in students for exam in students[student] ]
print(as_a_list)

EDIT (answering questions in the comments): I'm not sure what you mean by "empty list as a dictionary". In Python, a list and a dictionary are two different things. In your original example after "This is what I'd like my result to look like:", you have a tuple, not a dictionary (nor a list). Note that the whole thing is enclosed by parentheses, not braces. If you want student_grades to be a dictionary too, then the next question is what you want its keys to be. If you want them to be the student names, then how would you want it to be any different from the initial dictionary called student?

Upvotes: 2

Related Questions