通过字典键的动态操作

4
我需要在Python中操作动态字典。我有来自输入信息的未识别信息,就像这个例子中一样:
   'properties[props][defaultValue]': ''
   'properties[props][dt_precision]': ''
   'properties[props][dt_table]': ''
   'properties[props][dtfield]': ''

我需要转换成这个示例的字典:

properties['props']['dt_table'] = 1
properties['props']['dt_table'] = 2

我不知道真正的信息,但我知道格式是这样的:

variable[index] = value 
variable[index][index_1] = value
variable[index][index_1] [index_2]= value
variable[index][index_1] [index_2][index_3]= value

我的问题是,如何添加一个具有无限层级键的字典?换句话说,动态地向子键添加大量的子键层次结构。
在JavaScript中,我使用类似于以下引用:
f=var['key'];
f['key'] = {};
f = f['key'];
f['key'] = 120;

这让我能够构建:

var['key']['key'] = 120

但是在Python中的等价物却无法正常工作。


3
可以在Python中实现自动创建嵌套数据结构的功能(即Autovivification)。 - martineau
1个回答

2

天真的方法

最简单的方法是手动在每个子级别上创建新字典:

var = {}
var['key'] = {}
var['key']['key'] = 120

print(var['key']['key'])
print(var)

这将产生以下输出:

120
{'key': {'key': 120}}

自动创建数据结构

您可以通过使用defaultdict来自动化它,如@martineau在评论中建议的那样:

from collections import defaultdict

def tree():
    return defaultdict(tree)

v2 = tree()
v2['key']['key'] = 120

print(v2['key']['key'])
print(v2)

输出结果:

120
defaultdict(<function tree at 0x1ae7d88>, {'key': defaultdict(<function tree at 0x1ae7d88>, {'key': 120})})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接