改用collections.defaultdict() 对象:
from collections import defaultdict
def tree():
return defaultdict(tree)
nested = defaultdict(tree)
for word in words:
node = nested
for char in word:
node = node[char.upper()]
每当您尝试访问 defaultdict 中尚不存在的键时,都会调用默认工厂以透明地为该键生成值。在上面的代码中,默认工厂是tree(),它使用相同的工厂生成另一个 defaultdict(),让您只需访问键即可构建嵌套的字典集。
演示:
>>> from collections import defaultdict
>>> def tree():
... return defaultdict(tree)
...
>>> nested = defaultdict(tree)
>>> words = ['Apple','Ape','Bark','Barn']
>>> for word in words:
... node = nested
... for char in word:
... node = node[char.upper()]
...
>>> nested
defaultdict(<function tree at 0x114e62320>, {'A': defaultdict(<function tree at 0x114e62320>, {'P': defaultdict(<function tree at 0x114e62320>, {'P': defaultdict(<function tree at 0x114e62320>, {'L': defaultdict(<function tree at 0x114e62320>, {'E': defaultdict(<function tree at 0x114e62320>, {})})}), 'E': defaultdict(<function tree at 0x114e62320>, {})})}), 'B': defaultdict(<function tree at 0x114e62320>, {'A': defaultdict(<function tree at 0x114e62320>, {'R': defaultdict(<function tree at 0x114e62320>, {'K': defaultdict(<function tree at 0x114e62320>, {}), 'N': defaultdict(<function tree at 0x114e62320>, {})})})})})
>>> def print_nested(d, indent=0):
... for k, v in d.iteritems():
... print '{}{!r}:'.format(indent * ' ', k)
... print_nested(v, indent + 1)
...
>>> print_nested(nested)
'A':
'P':
'P':
'L':
'E':
'E':
'B':
'A':
'R':
'K':
'N':
defaultdict 是标准 Python 字典的子类,除了自动实现键值外,其行为与常规字典完全相同。