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



我有两个Python字典,我想写一个表达式来返回这两个合并后的字典。我需要跟随输入和输出

假设我们比较两个句子我喜欢吃土豆。和"我喜欢西红柿">

输入

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}

最好的方法是什么?

试试这个(python 3.9+ for|字典合并操作符):

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

最新更新