【问题标题】:dict update updating the nested key value pair [duplicate]dict update 更新嵌套键值对[重复]
【发布时间】:2021-09-12 21:18:26
【问题描述】:

我有一本原始字典 - student = {"name":"Mike","class":{"grade":10,"section":"b"}}。现在,我有另一个new_dict = {"class":{"grade":10, "section":"c"}}

现在,我想用 new_dict 更新我的学生字典以匹配键,student.update(new_dict) 工作正常。但是我可能遇到new_dict = "class":{"section":"d"} 之类的情况,当我提供更新时,它会更新学生的字典,而"grade":10 会丢失。

student = {"name":"Mike","class":{"grade":10,"section":"b"}}
new_dict = {"class":{"section":"c"}}
student.update(new_dict)

Actual output:
=============
print(student)
{'name': 'Mike', 'class': {'section': 'c'}}

Expected output:
================
{'name': 'Mike', 'class': {"grade":10,'section': 'c'}}

在这种情况下进行更新的最佳方法是什么,在所有键和条目中更新并仅更新匹配的键和值(即使它在嵌套内部)。

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    也许您可以迭代 new_dict 并在元素内部进行更新。

    student = {"name":"Mike","class":{"grade":10,"section":"b"}}
    new_dict = {"class":{"section":"c"}}
    
    
    for k, v in new_dict.items():
        student[k].update(v)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-22
      • 2018-11-07
      • 2018-11-23
      • 1970-01-01
      • 2020-07-22
      • 2014-06-21
      • 2021-05-04
      相关资源
      最近更新 更多