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

Time:01-07

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)

CodePudding user response:

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

CodePudding user response:

It sounds like you might be running into an issue with variable scoping in your loop. When you define a variable inside a loop and then try to access it outside of the loop, the variable might not be defined or might have a different value than you expect.

Here is an example of what I mean:

my_dict = {'a': 1, 'b': 2, 'c': 3}

for key in my_dict:
    value = my_dict[key]
    print(key, value)

print(value)  # value is defined here, but it has the value of the last item in the dict

In the example above, the loop defines the value variable and assigns it the value of each item in the dictionary as the loop iterates. However, when we try to print the value variable outside of the loop, it has the value of the last item in the dictionary because the loop has been completed and the value variable has been reassigned multiple times.

To fix this issue, you can define the variable outside of the loop so that it is in the correct scope, like this:

my_dict = {'a': 1, 'b': 2, 'c': 3}

value = None
for key in my_dict:
    value = my_dict[key]
    print(key, value)

print(value)  # value is defined here and has the correct value

I hope this helps! Let me know if you have any other questions or if you need further assistance.

  • Related