1

I have a dictionary whose values are a two-element-list. And I want to increment only one value of a certain key inside the dictionary. Here is what I tried:

my_dict = dict.fromkeys(range(0,24,2), [0,0])
my_test_key = 2
print(my_dict)
my_dict[my_test_key][0]+=1
print(my_dict)

This shows the following:

{0: [0, 0], 2: [0, 0], 4: [0, 0], 6: [0, 0], 8: [0, 0], 10: [0, 0], 12: [0, 0], 14: [0, 0], 16: [0, 0], 18: [0, 0], 20: [0, 0], 22: [0, 0]}
{0: [1, 0], 2: [1, 0], 4: [1, 0], 6: [1, 0], 8: [1, 0], 10: [1, 0], 12: [1, 0], 14: [1, 0], 16: [1, 0], 18: [1, 0], 20: [1, 0], 22: [1, 0]}

Which means that it adds in every "[0]" position of every key. But what I want is:

{0: [0, 0], 2: [1, 0], 4: [0, 0], 6: [0, 0], 8: [0, 0], 10: [0, 0], 12: [0, 0], 14: [0, 0], 16: [0, 0], 18: [0, 0], 20: [0, 0], 22: [0, 0]}

Pleace notice how it should be, only changing "2: [1, 0]" when it was previously "2: [0, 0]"

Thank you in advance

Borzanagan
  • 11
  • 1
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – buran Nov 04 '21 at 21:38
  • 3
    Because there is only one list in your program. Every element in your dictionary has a reference to that one list. You can use a list comprehension to build your dict: `my_diict = dict((i,[0,0]) for i in range(0,24,2))`. – Tim Roberts Nov 04 '21 at 21:38
  • ```>>> id(my_dict[2]) 123145300839872 >>> id(my_dict[0]) 123145300839872 >>>``` So you are storing reference to the same list. You change one, you change them all. – Dilawar Nov 04 '21 at 21:39

1 Answers1

1

Note that in your initialization of my_dict, you are storing the reference of a list in 12 places. Change any one of them, and all will point to the new value.

You can use id() to check if two variables points to the same thing.

>>> id(my_dict[2])
123145300839872
>>> id(my_dict[0])
123145300839872

Here my_dict[0] and my_dict[2] are essentially the same: any change to one will reflect in another.

Here is one way to achieve what you want.

>>> my_dict = { x : [0, 0] for x in range(0,24,2) }
>>> my_dict
{0: [0, 0], 2: [0, 0], 4: [0, 0], 6: [0, 0], 8: [0, 0], 10: [0, 0], 12: [0, 0], 14: [0, 0], 16: [0, 0], 18: [0, 0], 20: [0, 0], 22: [0, 0]}
>>> my_dict[2][0] += 1
>>> my_dict
{0: [0, 0], 2: [1, 0], 4: [0, 0], 6: [0, 0], 8: [0, 0], 10: [0, 0], 12: [0, 0], 14: [0, 0], 16: [0, 0], 18: [0, 0], 20: [0, 0], 22: [0, 0]}
>>>
Dilawar
  • 5,438
  • 9
  • 45
  • 58