问题
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
回答1:
It's a little tricky. You make a defaultdict of defaultdicts, like so:
defaultdict(lambda: defaultdict(list))
回答2:
Slightly faster than using a lambda
:
defaultdict(defaultdict(list).copy)
This has the same observable behavior as wim's answer, but avoids a lambda
in favor of a (in CPython) bound built-in method implemented in C, which means default value generation doesn't have to execute any Python byte code or look up any names, and it runs a small amount faster. In microbenchmarks, it looks like the cost paid when a key did not exist at access time is about 5-10% lower this way than with the otherwise equivalent lambda
.
Really, the reason I prefer it is because I hate lambda
due to people overusing it when it's a bad idea (e.g. map
/filter
with lambda
is always more verbose and slower than an equivalent listcomp/genexpr, but people keep doing it anyway for no discernible reason), even though in this case it hardly matters.
回答3:
You may have to do like this.
>>> from collections import defaultdict
>>> a=defaultdict()
>>> a["testkey"]=None
>>> a["testkey"]=defaultdict(list)
>>> a["testkey"]["list"]=["a","b","c"]
>>> a
defaultdict(None, {'testkey': defaultdict(<type 'list'>, {'list': ['a', 'b', 'c']})})
来源:https://stackoverflow.com/questions/33080869/python-how-to-create-a-dict-of-dict-of-list-with-defaultdict