Reputation: 11
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
Upvotes: 1
Views: 328
Reputation: 5645
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]}
>>>
Upvotes: 1