Reputation: 6293
I have a list of keys and want to create a dictionary that looks as follows:
d = {"a":[] ,"b":[] ,"c":[] ,"d":[]}
If i try something like this:
keys = ['a','b','c','d']
d = dict(zip(keys,[[]]*len(keys)))
it creates the dictionary just fine, except all lists are references to the same object, so if I try d['c'].append('one')
then it gets appended to all four lists.
I solved it using dict comprehension
(for those interested: d = {k : [] for k in keys}
) but wondering if there's a more efficient way?
Edit: yes I KNOW it's a dict comprehension. That was a typo obviously.
Upvotes: 3
Views: 4353
Reputation: 48077
Dict comprehensions are pretty efficient (and it is not the list comprehension as mentioned by you). I would suggest to go with the dict comprehension. Surely there are few alternatives to achieve this, but they won't be as efficient as the one you mentioned.
Below is the timeit
comparison of your alternative solution using zip
(even though I know that it doesn't works the way you expect) and the one using dict comparison on Python 2.7:
# Using dict comprehension --> 0.415 usec
mquadri$ python -m "timeit" -s "keys=keys = ['a','b','c','d']" "{key: [] for key in keys}"
1000000 loops, best of 3: 0.415 usec per loop
# Using `dict`-`zip` conversion --> 1.48 usec
mquadri$ python -m "timeit" -s "keys=keys = ['a','b','c','d']" "dict(zip(keys,[[]]*len(keys)))"
1000000 loops, best of 3: 1.48 usec per loop
As you can see, dict comprehension approach is about three times faster and I doubt that there is any other more efficient way to achieve this.
Upvotes: 3
Reputation: 38415
keys = ['a','b','c','d']
d = dict((k,[]) for k in keys)
d['c'].append('one')
print(d)
You get
{'c': ['one'], 'a': [], 'b': [], 'd': []}
Upvotes: 1
Reputation: 2881
How about defaultdict:
from collections import defaultdict
data = defaultdict(list)
data['key'].append('a')
data['key'] # prints ['a']
This way you directly skip the dict iteration in the beginning.
Upvotes: 4