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..
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With