In a dictionary, i can't print the different values in the loop. I print the same value for all elements

Question:

The code prints x for each element of the loop, but the problem is that it prints the same value of x for all elements, so the same number for everyone.

Instead if inside mydict, instead of x i use sum(value)/ len(value) for key,value in mylist.items(), then the values are printed correctly.

But i want the variable x created in the second line and use them in mydict.

How can i use x inside mydict and correctly print all values for each element of the list?

Important: i don’t want to directly write sum(value)/ len(value) for key,value in list.items(), but i would use x

mylist = {('Jack', 'Grace', 8, 9, '15:00'): [0, 1, 1, 5], 
         ('William', 'Dawson', 8, 9, '18:00'): [1, 2, 3, 4], 
         ('Natasha', 'Jonson', 8, 9, '20:45'): [0, 1, 1, 2]
         }

    for key, value in mylist.items():
        x= sum(value)/ len(value)

        mydict = {key:
                x for key,value in mylist.items()}
    print(mydict)
Asked By: Takao貴男

||

Answers:

When you use list comprehension, you are effectively initiating a for loop. In your example x is calculated and then dict is created without the x term being re-calculated for each term. I don’t know why you use a for loop AND list comprehension together. You are creating a new dict with each iteration of the for loop but with a new x value that is assigned to each of the keys in you list comprehension. Just use ONE – list comprehension. ie

dict = {key: sum(value)/ len(value) for key,value in list.items()}
Answered By: Galo do Leste

Like what Nitesh, Christian, John, and Karl said, you are updating the entire list instead of just a single element, it’s just that scope is not the fix. X is becoming the value of each key of mydict each time, rather than only for that specific key/value pair. Just assign x to each key separately:

mylist = {('Jack', 'Grace', 8, 9, '15:00'): [0, 1, 1, 5], 
         ('William', 'Dawson', 8, 9, '18:00'): [1, 2, 3, 4], 
         ('Natasha', 'Jonson', 8, 9, '20:45'): [0, 1, 1, 2]
         }

mydict = {} # initialize mydict

for key, value in mylist.items():
    x= sum(value)/ len(value)
    mydict[key] = x # assign x to key

print(mydict)

and here’s the output:

{('Jack', 'Grace', 8, 9, '15:00'): 1.75, ('William', 'Dawson', 8, 9, '18:00'): 2.5, ('Natasha', 'Jonson', 8, 9, '20:45'): 1.0}
Answered By: Pranav