Defaultdict tuple of lists

I like defaultdict, but I want it to auto-generate 2 tuples of lists, and I'm not sure if this is possible. Therefore I want:

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

is it do-able with defaultdict?

+3
source share
4 answers

Of course. You need to specify a defaultdict function that returns what you want by default; The easiest way to create such a one-time function is with a lambda:

foo = defaultdict(lambda: ([], []))
foo['key1'][0].append('value')
+3
source
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']})})
+1
source
foo = defaultdict(lambda: ([], []))
+1
source

defaultdictfrom list 2-tuple? Just write the same thing in python:

dd = defaultdict(lambda: ([], []))
+1
source

All Articles