python - 将键,值动态添加到python中的字典

标签 python python-3.x algorithm recursion data-structures

给定列表中的路径(键),需要向给定字典添加值

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'}}}

关于python - 将键,值动态添加到python中的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56993846/

相关文章:

Python。从 data.frame 获取结构

python - 抓取YouTube channel 的前一天视频-bs4

python - 调用 `logging`会干扰其他模块

python-3.x - 在 Django 中未定义主键类型警告时使用的自动创建主键

c++ - 计算数组中总和存在的对数的算法

algorithm - 有效地在字符串中找到给定的子序列,最大化连续字符的数量

python扭曲的中间人实现

python - Networkx 中节点的组件数量

python - 从 S3 解压缩文件,写入 CSV 文件并推送回 S3

algorithm - 优化问题——寻找最大值