如何合并两个字典并将新键值设置为 0?

How to merge two dictionaries and setting new key values to 0?

我有两个 Python 字典,我想写一个 returns 这两个字典合并的表达式。我需要遵循输入和输出

假设我们比较两个句子 “我喜欢土豆”和 “我喜欢西红柿”

输入

dict1= {"I": 1, "like":1,"potatoes":1}
dict2= {"I": 1, "like":1,"tomatoes":1}

为了比较它们,我们需要在以下输出中使用它们

dict1 ={"I": 1, "like":1,"potatoes":1,"tomatoes":0}
dict2 ={"I": 1, "like":1,"potatoes":0,"tomatoes":1}

最好的方法是什么?

In [14]: dict1= {"I": 1, "like":1,"potatoes":1}
    ...: dict2= {"I": 1, "like":1,"tomatoes":1}

In [15]: keys1 = dict1.keys()  # dict keys are set-like: https://docs.python.org/3/library/stdtypes.html#dict-views

In [16]: keys2 = dict2.keys()  # get keys of dict2 in another set()

In [17]: dict1.update(dict.fromkeys(keys2 - keys1, 0))  # to build result from the items in dict1 and the "keys in dict2 but not in dict1" with value 0

In [18]: dict1
Out[18]: {'I': 1, 'like': 1, 'potatoes': 1, 'tomatoes': 0}

In [19]: dict2.update(dict.fromkeys(keys1 - keys2, 0))  # same here

In [20]: dict2
Out[20]: {'I': 1, 'like': 1, 'tomatoes': 1, 'potatoes': 0}

试试这个(python 3.9+ 用于 | 字典合并运算符):

dict1 = {"I": 1, "like": 1, "potatoes": 1}
dict2 = {"I": 1, "like": 1, "tomatoes": 1}

union = dict1 | dict2

res1 = {k: dict1.get(k, 0) for k in union}
res2 = {k: dict2.get(k, 0) for k in union}

print(res1)
print(res2)

输出:

{'I': 1, 'like': 1, 'potatoes': 1, 'tomatoes': 0}
{'I': 1, 'like': 1, 'potatoes': 0, 'tomatoes': 1}