Search code examples
pythondefaultdict

defaultdict tuple of lists


I like defaultdict, but I want it to autovivify a 2-tuple of lists and I'm not sure if it's possible. So what I want is:

foo = defaultdict(???)
foo['key1'][0].append('value')
foo['key1'][1].append('other value')

is this do-able with defaultdict?


Solution

  • Sure. You need to give defaultdict a function that returns what you want the default to be; the easiest way to create such a one-off function is a lambda:

    foo = defaultdict(lambda: ([], []))
    foo['key1'][0].append('value')