My attempt to programmatically create a dictionary of lists is failing to allow me to individually address dictionary keys. Whenever I create the dictionary of lists and try to append to one key, all of them are updated. Here’s a very simple test case:
data = {}
data = data.fromkeys(range(2),[])
data[1].append('hello')
print data
Actual result: {0: ['hello'], 1: ['hello']}
Expected result: {0: [], 1: ['hello']}
Here’s what works
data = {0:[],1:[]}
data[1].append('hello')
print data
Actual and Expected Result: {0: [], 1: ['hello']}
Why is the fromkeys method not working as expected?
When
[]is passed as the second argument todict.fromkeys(), all values in the resultingdictwill be the samelistobject.In Python 2.7 or above, use a dict comprehension instead:
In earlier versions of Python, there is no dict comprehension, but a list comprehension can be passed to the
dictconstructor instead:In 2.4-2.6, it is also possible to pass a generator expression to
dict, and the surrounding parentheses can be dropped: