Python如何更新dict而不覆盖其他值[重复]

Posted

技术标签:

【中文标题】Python如何更新dict而不覆盖其他值[重复]【英文标题】:Python how to update dict without overwriting other values [duplicate] 【发布时间】:2013-02-15 06:32:26 【问题描述】:

假设我有这个:

config = 
    "a": 
        "hello": 1,
        "goodbye": 2,
    

我想像这样将["a"]["hello"] 更新为 10:

update = 
    "a": 
        "hello": 10
    


config.update(update)

此时配置为:

config = 
    "a": 
        "hello": 10
    

如何在不覆盖其他值/子字典的情况下用另一个字典更新一个字典?

【问题讨论】:

为什么不只是config['a']['hello'] = 10 【参考方案1】:
config = 
    "a": 
        "hello": 1,
        "goodbye": 2,
    

你可以这样做:

config['a']['hello'] = 10

更新后的config

config = 
    "a": 
        "hello": 10,
        "goodbye": 2,
    

【讨论】:

以上是关于Python如何更新dict而不覆盖其他值[重复]的主要内容,如果未能解决你的问题,请参考以下文章