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?
Method #1 : Using {} + "*" operator We can create a list containing single empty dictionary and then multiply it by Number that is size of list. The drawback is that similar reference dictionaries will be made which will point to similar memory location.
How to Create An Empty Dictionary in Python. To create an empty dictionary, first create a variable name which will be the name of the dictionary. Then, assign the variable to an empty set of curly braces, {} . Another way of creating an empty dictionary is to use the dict() function without passing any arguments.
Another way to initialize a python dictionary is to use its built-in “dict()” function in the code. So, you have to declare a variable and assign it the “dict()” function as an input value. After this, the same print function is here to print out the initialized dictionary.
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))
Use defaultdict instead:
from collections import defaultdict data = defaultdict(list) data[1].append('hello')
This way you don't have to initialize all the keys you want to use to lists beforehand.
What is happening in your example is that you use one (mutable) list:
alist = [1] data = dict.fromkeys(range(2), alist) alist.append(2) print data
would output {0: [1, 2], 1: [1, 2]}
.
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