python - 将键,值动态添加到python中的字典
问题描述
给定列表中的路径(键),需要向给定字典添加值
data = {'personal_information': {'name' : {'first_name': 'Ashutosh'}}}
path_to_add = ['personal_information', 'address': 'state']
value = 'Delhi'
expected_output = {'personal_information': {'name' : {'first_name': 'Ashutosh'}}, 'address': {'state': 'Delhi'}}
解决方案
您可以使用递归来做到这一点:
data = {'personal_information': {'name' : {'first_name': 'Ashutosh'}}}
path_to_add = ['personal_information', 'address', 'state']
value = 'Delhi'
def addValue(dictionary, path, value):
if len(path) > 1:
if path[0] not in dictionary.keys():
dictionary[path[0]] = {}
addValue(dictionary[path[0]], path[1:], value)
else:
dictionary[path[0]] = value
print(data)
addValue(data, path_to_add, value)
print(data)
输出:
{'personal_information': {'name': {'first_name': 'Ashutosh'}}}
{'personal_information': {'name': {'first_name': 'Ashutosh'}, 'address': {'state': 'Delhi'}}}
推荐阅读
- php - 开发我的 Web 应用程序时出现 EasyAdmin Bundle 问题
- excel - 没有为具有数值的字符串参数调用 UDF
- javascript - 如果文本进入下一行,则截断文本(调整窗口大小)
- node.js - 如何在nodejs中保存文件?
- react-native - 远程交互式推送通知 - 如何?
- react-native - 在 React Native 中向组件添加子组件
- c++ - 现代Cmake找不到Eigen库依赖
- javascript - 单击时滚动到 Kendo Grid 行 - 出现意外的 JavaScript 错误
- c++ - TZ 时间的 C++ 结构,但没有日期?
- javascript - Requirejs 和 polyfill.io mishmash