Skip to content Skip to sidebar Skip to footer

Append Value To One List In Dictionary Appends Value To All Lists In Dictionary

The Problem I am creating a dictionary with empty lists as values in the following way. >>> words = dict.fromkeys(['coach', 'we', 'be'], []) The dictionary looks like thi

Solution 1:

dict.fromkeys uses the same object for all values, in this case a mutable list... That means, all keys share the same empty list... When you try to .append to the value of one list, the changes are made in-place to the object, so changes to it are visible by all that reference it.

If instead you used a dict-comp, eg: {k:[] for k in ['could', 'we', 'be']} each [] is a different empty list and so would be unique for each key value and work as expected.

In regards to using dict.fromkeys(['a', 'b', 'c'], 0) the 0 is an immutable object thus isn't subject to that gotcha as changes to it result in new objects, not a change to the underlying object which different names (in this case - the values of the different keys) may share.

Post a Comment for "Append Value To One List In Dictionary Appends Value To All Lists In Dictionary"