Search code examples
pythondictionarydata-structuresdefaultdict

Python how to create a dict of dict of list with defaultdict


How do I create a dict of dict of lists using defaultdict? I am getting the following error.

>>> from collections import defaultdict
>>> a=defaultdict()
>>> a["testkey"]=None
>>> a
defaultdict(None, {'testkey': None})
>>> a["testkey"]["list"]=[]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object does not support item assignment

Solution

  • It's a little tricky. You make a defaultdict of defaultdicts, like so:

    defaultdict(lambda: defaultdict(list))