在Python中初始化dict的最佳方法是什么? [英] What's the best way to initialize a dict of dicts in Python?
本文介绍了在Python中初始化dict的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Perl中很多次,我都会做类似的事情:
A lot of times in Perl, I'll do something like this:
$myhash{foo}{bar}{baz} = 1
我如何将其翻译成Python?到目前为止,我有:
How would I translate this to Python? So far I have:
if not 'foo' in myhash:
myhash['foo'] = {}
if not 'bar' in myhash['foo']:
myhash['foo']['bar'] = {}
myhash['foo']['bar']['baz'] = 1
有更好的方法吗?
推荐答案
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}}}
这篇关于在Python中初始化dict的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文