pythondefaultdictpython-collections

How to initialize defaultdict with keys?


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?


Solution

  • From the comments, I'm assuming you want a dictionary that fits the following conditions:

    1. Is initialized with set of keys with an empty list value for each
    2. Has defaultdict behavior that can initialize an empty list for non-existing keys

    @Aaron_lab has the right method, but there's a slightly cleaner way:

    d = defaultdict(list,{ k:[] for k in ('a','b','c') })