【问题标题】:Update values from a "default dictionary" without removing its keys [duplicate]从“默认字典”更新值而不删除其键[重复]
【发布时间】:2019-05-10 10:54:53
【问题描述】:

我有两个字典,第一个是第二个的默认值在不存在或未定义时应该回退到的值,有点像这样:

default_dict = {
    'lorem': {
        'foo': 'white',
        'bar': 'black',
    },
    'ipsum': {
        'xyz': '',
        'abc': {},
        'qwe': {}

    }
}

第二个看起来像这样:

custom_dict = {
    'lorem': {
        'bar': 'blue',
    },
    'ipsum': {
        'xyz': 'apple',
        'qwe': { 'one': 'strawberry' }

    }
}

我有什么方法可以从 default_dict 中“更新”custom_dict 中的值?

所需的结果如下所示:

custom_dict = {
    'lorem': {
        'foo': 'white',
        'bar': 'blue',
    },
    'ipsum': {
        'xyz': 'apple',
        'abc': {},
        'qwe': { 'one': 'strawberry' }

    }
}

我尝试过default_dict.update(custom_dict),然后是custom_dict = default_dict,但正如您可以想象的那样,我只是让custom_dict 原封不动...所以default_dict 的键在更新时会被删除。

【问题讨论】:

标签: python python-3.x


【解决方案1】:

如果您的字典结构始终如上,那么以下代码可以正常工作:

for item in default_dict:
    for value in default_dict[item].keys():
        if value not in custom_dict[item].keys():
            custom_dict[item].update({value: default_dict[item][value]})

祝你好运

【讨论】:

    【解决方案2】:

    用途:

    d={a:b for k,v in custom_dict.items() for a,b in v.items()}
    print({k:{a:d.get(a,b) for a,b in v.items()} for k,v in default_dict.items()})
    

    字典理解 + 嵌套字典理解会起作用。

    输出:

    {'lorem': {'foo': 'white', 'bar': 'blue'}, 'ipsum': {'xyz': 'apple', 'abc': {}, 'qwe': {'one': 'strawberry'}}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-26
      • 2020-05-09
      • 2011-07-06
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      • 2020-11-22
      相关资源
      最近更新 更多