Question
Asked By – Martin Burch
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?
Now we will see solution for issue: How can I initialize a dictionary of distinct empty lists in Python?
Answer
Passing []
as second argument to dict.fromkeys()
gives a rather useless result – all values in the dictionary will be the same list object.
In Python 2.7 or above, you can use a dicitonary comprehension instead:
data = {k: [] for k in range(2)}
In earlier versions of Python, you can use
data = dict((k, []) for k in range(2))
This question is answered By – Sven Marnach
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0