Home > Back-end >  Iterating a dictionary with list values (why does it iterate over the list)
Iterating a dictionary with list values (why does it iterate over the list)

Time:08-05

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])

CodePudding user response:

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():

CodePudding user response:

A for loop iterates over the keys of a dict. So this code:

for x in D:
    L = D[x]

Means that x is each key from the D.

Then L = D[x] fetches the corresponding list generated previously: D[studentId] = gradesList.split(",")

Better would be to iterate over the keys and values at once:

for x,L in D.items():
    s = 0
    ...
  • Related