python中的内置库collections中有个defaultdict,这个具体的用法就不说了,资料很多,确实好用。
但是想在嵌套的dict中使用defaultdict就比较麻烦了,正好在网上看到一个相关的, 使用递归解决了这个问题,非常的妙:
from collections import defaultdict
def tree():
return defaultdict(tree)
使用如下:
c = defaultdict(tree)
c['h']['username'] = 'xxx'
c['l']['username'] = 'xxxx'
这样即使嵌套很多层字典也不会有keyerror的问题了。
还可以通过重载符来实现:
#这个实现的方式更优雅
class Tree(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
tree = Tree()