gpt4 book ai didi

python : update value in nested dictonary after reading keys from list

转载 作者:太空宇宙 更新时间:2023-11-03 15:53:37 25 4
gpt4 key购买 nike

从列表中读取键后,我需要更新字典中的值。例如

d1 = {"sun":{"mon":"111"},"tue":{"wed":"222"},"thu":{"fri":{"sat":"333"}}} and l1 = ["thu","fri","sat"].

这里我需要将d1["thu"]["fri"]["sat"]的值更改为444

请告诉我如何编写一个以 d1、l1 和新值作为参数并返回更新后的字典的函数。

最佳答案

或者您可以创建一个新字典并用它来更新原始字典

def create_update_dict(keys, val):
if len(keys) == 1:
return {keys[0]: val}
else:
return {keys[0]: create_update_dict(keys[1:], val)}

def update_dict_val(d, val, keys):
update_dict = create_update_dict(keys, val)
d.update(update_dict)
return d

关于 python : update value in nested dictonary after reading keys from list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41007437/

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