仅从另一个字典更新字典中的键作为参考

only update key in dictionary from another dictionary as reference

为简单起见,我在下面有 2 部词典。我想更新第二个字典(但只是键)并参考第一个字典将值设置为 0。

原始词典:

dict1={'a': 1, 'b': 2, 'c': 3}
dict2 ={'a': 2, 'b': 2}

更新后:

dict1 ={'a': 1, 'b': 2, 'c': 3}
dict2 ={'a': 2, 'b': 2, 'c': 0}

您可以使用 dict2.update 和字典理解来执行此操作:

dict1={'a': 1, 'b': 2, 'c': 3}
dict2 ={'a': 2, 'b': 2}

dict2.update({k:0 for k,v in dict1.items() if k not in dict2})

print (dict1)
print (dict2)
{'a': 1, 'b': 2, 'c': 3}
{'a': 2, 'b': 2, 'c': 0}