0

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)
  • You're recreating `dict` as a fresh dictionary each time through the loop, which erases the previous contents of `dict`. – John Gordon Jan 07 '23 at 01:36
  • Note: do not use the name `dict` for a variable name. Same goes for things like `list`. – Chris Jan 07 '23 at 01:48
  • Please read [ask] and [mre], and make sure that someone else can **copy and paste** the code **without adding or changing anything** to **directly** see the **exact** problem. In this case: include some example value for `mylist` to start, and show the actual and expected results. – Karl Knechtel Jan 07 '23 at 01:49
  • @Chris I know it. That was just an example for the question, you're right. I edit! –  Jan 07 '23 at 01:50
  • Please also try to make sure the logic is clear. Where the code says `dict = {key: x for key,value in list.items()}`, do you want this to make the complete dictionary again from scratch? Or do you only want it to add a `key: x` pair for the current iteration of the loop? – Karl Knechtel Jan 07 '23 at 01:54
  • @KarlKnechtel OK done! Updated! I just want it to add x in the dictionary. The loop to create x needs to be executed where I wrote it in the code. This is the best performing solution right? –  Jan 07 '23 at 01:59
  • The purpose of a dict comprehension (`{... for ... in ...}`) is to create an entire dictionary all at once. If you have `key` as a key that you want to set in `mydict`, and `x` is the corresponding value, that is written: `mydict[key] = x`. I assume you have already seen something like this, and are simply overthinking the problem. Voting to close as a typo. – Karl Knechtel Jan 07 '23 at 02:04
  • its also not a good practice to put "list" in a variable name when it is not even a list in the first place – Codeman Jan 07 '23 at 02:52

2 Answers2

0

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()}
Galo do Leste
  • 703
  • 5
  • 13
  • That's no good. In my question I wrote that I also tried this (and it works), but that's not what I'm looking for. I want to call the calculation with the variable x. I don't want to directly write sum(value)/ len(value) for key,value in list.items(). You wrote me the code which I also wrote in my question. Read carefully please –  Jan 07 '23 at 01:43
  • 1
    what do you mean I want to call the calculation with the variable x. What calculation? I'm a bit confused as to what you are trying to do – Galo do Leste Jan 07 '23 at 01:47
  • "I want to call the calculation with the variable x". This does not make sense as written; but if I understand the meaning correctly, then no, it simply doesn't work like that. Please read [Why doesn't my "formula" variable update automatically, like in a spreadsheet? How can I re-compute the value?](https://stackoverflow.com/questions/75026816) and see if it clarifies the problem. – Karl Knechtel Jan 07 '23 at 01:52
  • Maybe it would be useful to think of list comprehension as a method that contains a for loop. You pass a single variable x as a parameter to that for loop. While that method runs you cannot tell the method to use a new a new value of x from outside the method. You can however recalculate x from within the method. So once you have passed a single x value to you list comprehension, you CANNOT change it while the list comprehension builds itself – Galo do Leste Jan 07 '23 at 01:59
  • @GalodoLeste The calculation is the sum(value)/ len(value) division. I simply want to put it in a variable x and use the variable x in mydict, so mydict = {key:x. Could you modify your code and show me a better solution please? Thank you –  Jan 07 '23 at 02:07
  • Are you saying you just want to add a new term ti myDict which is {key: x}. if so merely replace your list comprehension with myDict[key] = x – Galo do Leste Jan 07 '23 at 02:11
0

Like what Nitesh, Christian, John, Karl, and Galo 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}
Codeman
  • 109
  • 9
  • Maybe that's what I need, thanks :) A curiosity please: if i also write y = x / 2, how can i print this in the dictionary too? So get two value (1.75 and 0,87): {('Jack', 'Grace', 8, 9, '15:00'): 1.75, 0.87 ? Thanks and sorry –  Jan 07 '23 at 02:56
  • make another variable y in a new line after the line x is in, and then make "mydict[key] = x" become "mydict[key] = (x, y)" – Codeman Jan 07 '23 at 02:59
  • I'm asking you these questions to understand if the code you wrote is what I need. Now I have this output: {('Jack', 'Grace', 8, 9, '15:00'): (1.75, 0.875). The numbers 1.75 and 0.875 are both in the same parenthesis. If I wanted to call x and y individually and separately, how can I call them? Thank you. –  Jan 07 '23 at 03:04
  • @Takao貴男 please be specific: do you want a string, multiple dicts, or what are you wanting specifically? What data-type do you want? – Codeman Jan 07 '23 at 03:09
  • I simply want to add some values (x and y) in a dictionary and then I want to recall them to print them individually. For example now I would like to do something like this: mydict[x] or mydict[y], or mydict[0] or mydict[1]. So I'm trying to figure out if the code you wrote me is what I'm looking for. Sorry for the confusion, I'm new to Python. I will gladly accept your answer if you help me. Thank you –  Jan 07 '23 at 03:13
  • I add to the comment above: Then manage and access the keys and values of mydict, so as to call 1.75 and 0.875 for later use. Before the SO question, I used to use a list and tuples and access elements to extract each individual element. But tuples and lists are too slow, so I want to use a dictionary –  Jan 07 '23 at 03:17
  • If you want to access the values directly, then you may have to create a separate dictionary that stores the exact opposite: the 1.75 is one key who's value is {'Jack', 'Grace', 8., 9., '15:00'}, and 0.875 has the same value. This is because in python and many other languages, you need a for-loop to get the key a value is from, but a single get() to get the value of a key. – Codeman Jan 07 '23 at 03:22
  • If you just care about the formatting in the values however, an f-string or string.format should work. – Codeman Jan 07 '23 at 03:23
  • I need the opposite. I need the key is {'Jack', 'Grace', 8., 9., '15:00'} and the values 1.75 and 0.875. So in the future I may use 1.75 and 0.875 to call them in other algorithms, display them in a datagrid, etc. For example, before I decided to use dictionary, I used to use tuples and lists like this new.append([[key], [x], [y]]). Do you have any ideas how you can edit your question and help me? I will gladly accept your kind reply. –  Jan 07 '23 at 03:32
  • Again, you need a for loop if you want to access the key from the values 1.75 and 0.875. If I understand your request correctly, it may be best for the two values to be together, then a tuple/array should work fine as the value. Also, this discussion should be moved to a chat since it is slightly off the scope of your original question. – Codeman Jan 07 '23 at 03:36
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/250917/discussion-between-takao-and-pranav). –  Jan 07 '23 at 03:37
  • I'm not sure if that's the answer I needed (my miscommunication), but we got close. A thousand thanks –  Jan 07 '23 at 04:07