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

Loop through Python dictionary and add different values with same keys to a new dictionary

I am really stuck with this exercise. How can I with a for loop add the same keys with a new values to a different dictionary in Python?

Goal is to loops through student grades and replace them with "Excellent", "Bad", etc.

This is as far as I could get:

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

student_scores = {
  "Harry": 81,
  "Ron": 78,
  "Hermione": 99, 
  "Draco": 74,
  "Neville": 62,
}


student_grades = {}


for key, value in student_scores.items():
    print(key, value)


print(student_grades)

Much appreciated in advance!

>Solution :

You can add values to a dictionary by simply assigning the value to the dictionary indexed by the key. For example, student_grades["Harry"] = "Excellent"

You can do the same in your loop:

for key, value in student_scores.items():
    student_grades[key] = "Excellent"

if course, you’ll not assign the same value (grade) for all keys. Use an if statement or any other conditional logic to select which grade to assign to each student. For example:

for key, value in student_scores.items():
    if (value > 90)
        student_grades[key] = "Excellent"
    else
        student_grades[key] = "Okey-ish"
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