How to initialize defaultdict with keys?

Amir picture Amir · Mar 21, 2017 · Viewed 17.6k times · Source

I have a dictionary of lists, and it should be initialized with default keys. I guess, the code below is not good (I mean, it works, but I don't feel that it is written in the pythonic way):

d = {'a' : [], 'b' : [], 'c' : []}

So I want to use something more pythonic like defaultict:

d = defaultdict(list)

However, every tutorial that I've seen dynamically sets the new keys. But in my case all the keys should be defined from the start. I'm parsing other data structures, and I add values to my dictionary only if specific key in the structure also contains in my dictionary.

How can I set the default keys?

Answer

tdelaney picture tdelaney · Mar 21, 2017

That's already reasonable but you can shorten that up a bit with a dict comprehension that uses a standard list of keys.

>>> standard_keys = ['a', 'b', 'c']
>>> d1 = {key:[] for key in standard_keys}
>>> d2 = {key:[] for key in standard_keys}
>>> ...