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