给定列表中的路径(键),需要向给定字典添加值
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/