【发布时间】:2021-03-21 09:25:27
【问题描述】:
我正在使用 Python 中的一些重度嵌套字典,并尝试以递归方式更新它们。数据(代表 Nary 树)如下所示:
{
"root": {
"value": 1.0,
"name": null,
"children": [
{
"value": 0.5,
"name": null,
"children": [
{
"value": 0.5,
"name": null,
"children": []
},
{
"value": 3.0,
"name": "B",
"children": []
}
]
}
]
}
}
字典的每一层都有一个值和名称键。 我希望这两个键的每个实例(即每个级别)都成为附加 subdict 的值(例如,名称为“text”),即数据需要看起来像:
{
"root": {
"text": {
"value": 1.0,
"name": null,
},
"children": [
{
"text": {
"value": 0.5,
"name": null,
},
"children": [
{
"text": {
"value": 0.5,
"name": null,
},
"children": []
},
{
"text": {
"value": 3.0,
"name": "B",
},
"children": []
}
]
}
]
}
}
我确信这很容易做到,但我似乎无法解决!我尝试了几种使用递归的不同方法,但遇到了很多错误。 (如果使用 javascript 中的 JSON.parse 更容易做到这一点,那也很好。)任何帮助将不胜感激。下面的 非常错误 解决方案是我第一次尝试,但它显然不起作用,因为它不完整;我不确定如何以这种递归方式在同一迭代中访问两个键并在同一迭代中更新字典。
def add_encapsulation(json_input, lookup_key1, lookup_key2):
for key, val in json_input.items():
updated_key = "text"
subdict = dict()
if key == lookup_key1:
vals[key] = json_input["value"]
elif key == lookup_key2:
vals[key] = json_input["name"]
# I can't access the two keys in the same iteration, so you can't add them
# to the subdict. Also, how can you add the subdict to the dict at the appropriate place?
else:
add_encapsulation(v, lookup_key1, lookup_key2)
【问题讨论】:
-
首先显示您的代码和完整的错误消息。
-
@furas 我添加了我的尝试,但它显然已损坏/不完整——现在我的具体问题已被记录。
标签: python json dictionary recursion