3 回答

TA贡献1871条经验 获得超13个赞
class AutoVivification(dict):
"""Implementation of perl's autovivification feature."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
测试:
a = AutoVivification()
a[1][2][3] = 4
a[1][3][3] = 5
a[1][2]['test'] = 6
print a
输出:
{1: {2: {'test': 6, 3: 4}, 3: {3: 5}}}

TA贡献1804条经验 获得超7个赞
如果您需要的嵌套量是固定的,那就collections.defaultdict太棒了。
例如筑巢两个深:
myhash = collections.defaultdict(dict)
myhash[1][2] = 3
myhash[1][3] = 13
myhash[2][4] = 9
如果你想进入另一层嵌套,你需要做类似的事情:
myhash = collections.defaultdict(lambda : collections.defaultdict(dict))
myhash[1][2][3] = 4
myhash[1][3][3] = 5
myhash[1][2]['test'] = 6
编辑:MizardX指出我们可以通过一个简单的函数获得完全的通用性:
import collections
def makehash():
return collections.defaultdict(makehash)
现在我们可以做到:
myhash = makehash()
myhash[1][2] = 4
myhash[1][3] = 8
myhash[2][5][8] = 17
# etc

TA贡献1872条经验 获得超3个赞
是否有理由需要成为决定词?如果这个特定结构没有令人信服的理由,你可以简单地用一个元组索引dict:
mydict = {('foo', 'bar', 'baz'):1} # Initializes dict with a key/value pair
mydict[('foo', 'bar', 'baz')] # Returns 1
mydict[('foo', 'unbar')] = 2 # Sets a value for a new key
如果使用元组键初始化dict,则必须使用括号,但在使用[]设置/获取值时可以省略它们:
mydict = {} # Initialized the dict
mydict['foo', 'bar', 'baz'] = 1 # Sets a value
mydict['foo', 'bar', 'baz'] # Returns 1
添加回答
举报