Question

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?

Was it helpful?

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')

OTHER TIPS

from collections import defaultdict
foo = defaultdict(lambda: defaultdict(list))
foo['key1'][0].append('value')
foo['key1'][1].append('other value')
print foo

Output

defaultdict(<function <lambda> at 0x7f7b65b4f848>, {'key1': defaultdict(<type 'list'>, {0: ['value'], 1: ['other value']})})
foo = defaultdict(lambda: ([], []))

defaultdict of a list 2-tuple? Just write the same thing, in python:

dd = defaultdict(lambda: ([], []))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top