Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing one dict value changes all values

I am seeing some unusual behavior in Python dictionary:

import numpy as np
td =[np.Inf, 2, 3]
a = {}
# First initialize contents of dictionary to a list of values
for k in range(10):
    a[k] = td

# now I want to access the contents to modify them based on certain criteria 
for k in range(10):
    c = a[k]
    c[0] = k
    a[k] = c

From this I would expect each first item of the list for each dictionary key value to be changed based on (c[0] = k), however, what I get at the end is that all values of the dictionary are updated to the last value of k, as in:

{0: [9, 2, 3], 1: [9, 2, 3], 2: [9, 2, 3], 3: [9, 2, 3], 
 4: [9, 2, 3], 5: [9, 2, 3], 6: [9, 2, 3], 7: [9, 2, 3], 
 8: [9, 2, 3], 9: [9, 2, 3]}

Am I missing something, or there is something wrong in the dictionary definition?

I can work around this in a different way for my code to run, but I am interested as to why the dictionary class would behave this way.

like image 643
Nader Avatar asked Jul 17 '26 19:07

Nader


1 Answers

Because each key gets the same list... To make a shallow copy of the list, use the following syntax:

for k in range(10):
    a[k] = td[:] 

Demo:

>>> d = {}
>>> el = [1, 2, 3]
>>> d[0] = el
>>> d[1] = el
>>> map(id, d.values())
[28358416, 28358416]
like image 66
Jon Clements Avatar answered Jul 19 '26 09:07

Jon Clements



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!