【问题标题】:Python how to update dict without overwriting other values [duplicate]Python如何更新dict而不覆盖其他值[重复]
【发布时间】: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

标签: python dictionary


【解决方案1】:
config = {
    "a": {
        "hello": 1,
        "goodbye": 2,
    }
}

你可以这样做:

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

更新后的config

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

【讨论】:

    猜你喜欢
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    • 2020-04-14
    • 2020-03-01
    • 2020-02-24
    • 2017-09-13
    相关资源
    最近更新 更多