首页 > 解决方案 > 将键,值动态添加到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'}}

标签: pythonpython-3.xalgorithmrecursiondata-structures

解决方案


您可以使用递归来做到这一点:

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

推荐阅读