gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:06:20 28 4
gpt4 key购买 nike

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

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com