python - 在 Python 中使用 keypath 创建嵌套字典
问题描述
有一个具有多级键的嵌套字典。要求是:
- 如果 keypath 不存在,则使用 keypath 创建嵌套键
- 如果存在,则使用 keypath 更新值
例如,这是字典:
{
"animal": {
"dog": {
"type": "beagle"
}
},
"man": {
"name": "john",
"age": 36
},
"plant": {
"fruit": {
"apple": {
"type": "gala"
}
}
}
}
以下是更新值或附加新嵌套键路径的函数:
appendDict(["man", "name"], "daniel", json_dict)
appendDict(["computer", "laptop", "maker"], "hp", json_dict)
这是预期的结果:
{
"animal": {
"dog": {
"type": "beagle"
}
},
"man": {
"name": "daniel",
"age": 36
},
"plant": {
"fruit": {
"apple": {
"type": "gala"
}
}
},
"computer": {
"laptop": {
"maker": "hp"
}
}
}
我的问题是如何实现 appendDict() 函数以支持要求?
到目前为止,这是我的代码,但它还不起作用:
json_dict = {
"animal": {"dog": {"type": "beagle"}},
"man": {"name": "john", "age": 36},
"plant": {"fruit": {"apple": {"type": "gala"}}}
}
def appendDict(keys, value, json_dict):
for index, key in enumerate(keys):
if key not in json_dict:
if index == len(keys) - 1:
some_data = {}
some_data[key] = value
json_dict[key] = some_data
else:
some_data = {}
json_dict[key] = some_data
else:
json_dict[key] = value
appendDict(["man", "name"], "daniel", json_dict)
appendDict(["computer", "laptop", "maker"], "hp", json_dict)
解决方案
keys
您可以通过在每次调用时切片来使用递归:
def appendDict(keys, value, json_dict):
if len(keys) == 1:
json_dict[keys[0]] = value
else:
if keys[0] not in json_dict:
json_dict[keys[0]] = {}
appendDict(keys[1:], value, json_dict[keys[0]])
json_dict = {'animal': {'dog': {'type': 'beagle'}}, 'man': {'name': 'john', 'age': 36}, 'plant': {'fruit': {'apple': {'type': 'gala'}}}}
appendDict(["man", "name"], "daniel", json_dict)
appendDict(["computer", "laptop", "maker"], "hp", json_dict)
import json
print(json.dumps(json_dict, indent=4))
输出:
{
"animal": {
"dog": {
"type": "beagle"
}
},
"man": {
"name": "daniel",
"age": 36
},
"plant": {
"fruit": {
"apple": {
"type": "gala"
}
}
},
"computer": {
"laptop": {
"maker": "hp"
}
}
}
推荐阅读
- java - java swing表单中的必填文本字段
- javascript - 如何在向下滚动内容时修复导航菜单(二级菜单)?
- scala - 关于 akka 流的聚合指标
- java - 有什么方法可以将 String[] 转换为 List
> 在java中? - java - 我可以在字符串上使用 mod 吗?
- ios - Chrome 中带有音乐的 HTML 5 视频在 Safari 中没有音乐
- c - 使用 3 个线程进行信号处理时,谁是第 4 个线程
- python - 如何在不使用 Matplotlib FuncAnimation 的情况下创建实时图形
- shopify - 如何在结帐页面中使用液体获取所有商店运输方式 ID 或运输区域
- sql - 如何根据列值创建重复行