blueSurfer
blueSurfer

Reputation: 5821

Increment of an element in a dictionary of list in Python

I have this trivial code:

M = dict.fromkeys([0, 1, 2, 3, 4], [0, 0])
M[0][1] += 2
print(M)

Why is this the output?

{0: [0, 2], 1: [0, 2], 2: [0, 2], 3: [0, 2], 4: [0, 2]}

It increment all elements of the lists in the dictionary! I want to increment just the second element of the list with key 0, something like this:

{0: [0, 2], 1: [0, 0], 2: [0, 0], 3: [0, 0], 4: [0, 0]}

Upvotes: 3

Views: 1358

Answers (1)

Niklas B.
Niklas B.

Reputation: 95288

all the values in M point to the exact same list. Proof:

>>> map(id, M.values())
[139986331512912, 139986331512912, 139986331512912, 139986331512912, 139986331512912]

If you change it, it will affect all keys. Try creating a new list for every key:

>>> M = { k:[0,0] for k in [0, 1, 2, 3, 4] }
>>> M[0][1] += 2
>>> print(M)
{0: [0, 2], 1: [0, 0], 2: [0, 0], 3: [0, 0], 4: [0, 0]}

Upvotes: 10

Related Questions