Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does updating a dict that was appended to a list change the list?

My code will be more clear I think-

someList = list()
foo = {'a':'b'}
someList.append(foo)
print someList
>>> [{'a':'b'}]
defaultbazz = {'a':2, 'b':'t', 'c':'gg'}

for k, v in defaultbazz.iteritems():
    foo[k] = v

print someList
>>> [{'a': 2, 'c': 'gg', 'b': 't'}]

Shouldn't the last print be [{'a':'b'}]? I didn't updated the someList, I want it as is..

It's seems to me uninterpreted behavior..

But if that's how python works, how can I find workaround? Even setting a new dict updates the original one dict.. I mean:

someList = list()
foo = {'a':'b'}
someList.append(foo)
print someList
>>> [{'a':'b'}]
bar = foo
defaultbazz = {'a':2, 'b':'t', 'c':'gg'}

for k, v in defaultbazz.iteritems():
    bar[k] = v

print someList
>>> [{'a': 2, 'c': 'gg', 'b': 't'}]

I'll be thankful if someone can maybe explain me why it's happen..

like image 750
eligro Avatar asked Nov 29 '22 02:11

eligro


1 Answers

It looks like you are expecting your dict to be copied when you add it to a list or assign it to a new variable, but that is not how Python operates. If you assign a dict -- actually, if you assign any object -- you are not creating a new object, but instead you are simply giving your object a new name. (An object can have multiple names.)

So, when you edit your object under the new name, the single instance of that object changes, and that change is visible when you access the object through any name.

If you want to copy your object, then you can do this:

bar = dict(foo)

or

bar = foo.copy()
like image 98
Andrew Gorcester Avatar answered Dec 08 '22 00:12

Andrew Gorcester