Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从“更新值”;默认词典;不取下钥匙_Python_Python 3.x - Fatal编程技术网

Python 从“更新值”;默认词典;不取下钥匙

Python 从“更新值”;默认词典;不取下钥匙,python,python-3.x,Python,Python 3.x,我有两个字典,第一个是第二个字典的默认值,如果它们不存在或没有定义,那么它们应该返回到什么,这有点像这样: default_dict = { 'lorem': { 'foo': 'white', 'bar': 'black', }, 'ipsum': { 'xyz': '', 'abc': {}, 'qwe': {} } } custom_dict = { 'lorem':

我有两个字典,第一个是第二个字典的默认值,如果它们不存在或没有定义,那么它们应该返回到什么,这有点像这样:

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

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

    }
}
第二个看起来像这样:

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

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

    }
}
是否有任何方法可以使用
自定义dict
中的值从
默认dict
中“更新”?

期望的结果如下所示:

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

    }
}
我试过做
default\u dict.update(custom\u dict)
,然后
custom\u dict=default\u dict
,但你可以想象,我只是把
custom\u dict
原封不动地拿回来。。。因此,
default\u dict
的键在更新时会被删除。

使用:

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'}}}

如果词典的结构始终与上述相同,则以下代码可以正常工作:

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]})
祝你好运