Skip to content Skip to sidebar Skip to footer

Python Dict.fromkeys Return Same Id Element

When i do this on python i update all keys in one time. >>> base = {} >>> keys = ['a', 'b', 'c'] >>> base.update(dict.fromkeys(keys, {})) >>> ba

Solution 1:

When you initialize the value for the new keys as {} a new dictionary is created and a reference to this dictionary is becoming the values. There is only one dictionary and so if you change one, you will change "all".

Solution 2:

I tried it with both Python 2.7.6 and 3.4.3. I get the same answer when either get('a') or ['a'] is used. Appreciate if you can verify this at your end. Python does object reuse. Thus, dict.fromkeys() reuses the same empty dict is to initialize. To make each one a separate object, you can do this:

base.update(zip(keys, ({} for_ in keys)))

Post a Comment for "Python Dict.fromkeys Return Same Id Element"