Search code examples
pythonlambdadefaultdict

How to create a specific default list in defaultdict?


I am trying to build a defaultdict which is initialized with a specific list. Such that if I access the dict using a key that does exist, it will be initialized with a specific list, let's say [True, True, True].

Instead of doing this

my_defaultdict = collections.defaultdict(list)

So, for example, something like this (obviously would not work)

my_defaultdict = collections.defaultdict([True, True, True])

I tried something like this, but this does not work

my_defaultdict = collections.defaultdict(lambda: list[True, True, True])

I looked in this question for a start, but could not figure it out.


Solution

  • defaultdict's argument should be a function or any callable object:

    my_defaultdict = collections.defaultdict(lambda : [True,True,True])