Skip to content
Advertisement

Iterating a dictionary with list values (why does it iterate over the list)

I’m pretty new to programming and I’m starting with python

Why is it that the ‘for’ loop is iterating over the list and not over the key of the dictionary?

The intention is that the loop iterates over the list but I don’t understand why it’s happening if ‘for’ loops are supposed to iterate over the keys and not over the values

def getUserData():
    D = {}
    while True:
        studentId = input("Enter student ID: ")
        gradesList = input("Enter the grades by comma separated values: ")
        moreStudents = input("Enter 'no' to quit insertion or 'yes' to add more student info: ")
        if studentId in D:
            print(studentId, "is already inserted")
        else:
            D[studentId] = gradesList.split(",")
        if moreStudents.lower() == "no":
            return D
        elif moreStudents.lower() == "yes":
            pass


studentData = getUserData()


def getAvgGrades(D):
    avgGrades = {}
    for x in D:
        L = D[x] <------------------- #This is specifically what I don't understand
        s = 0
        for grades in L:
            s = s + int(grades)
        avgGrades[x] = s/len(L)
    return avgGrades


avgG = getAvgGrades(studentData)


for x in avgG:
    print("Student:", x, "got avg grades as: ", avgG[x])

Advertisement

Answer

When you iterate over a dict like so:

for x in D:

You actually do this:

for x in D.keys(): # you iterate over the keys

To get the key and the value, simply do this:

for k, v in D.items():
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement