在Perl中,很多时候我会这样做:
$myhash{foo}{bar}{baz} = 1
我该如何将其转换为Python?到目前为止,我有:
if not 'foo' in myhash:
myhash['foo'] = {}
if not 'bar' in myhash['foo']:
myhash['foo']['bar'] = {}
myhash['foo']['bar']['baz'] = 1
有没有更好的方法?
发布于 2009-03-16 19:45:34
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}}}
发布于 2009-03-16 21:29:44
如果您需要的嵌套数量是固定的,那么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
发布于 2009-03-16 19:56:22
这是不是需要一个字典的原因?如果对于特定的结构没有令人信服的原因,您可以简单地使用元组对字典进行索引:
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
https://stackoverflow.com/questions/651794
复制相似问题