我有兩個Python字典,我想寫一個運算式來回傳這兩個合并的字典。我需要有以下的輸入和輸出
。假設我們比較兩個句子 "我喜歡土豆 "和 "我喜歡西紅柿"
輸入
dict1= {"I"/span>。1, "like":1," potatoes":1}。
dict2= {"I": 1, "like":1," tomatoes":1}。
為了比較它們,我們需要它們在以下輸出中進行比較
dict1 ={"I"/span>: 1, "like":1, "potatoes": 1,"Tomatoes":0}。
dict2 ={"I": 1, "like":1, "potatoes": 0,"番茄":1}。
什么是最好的方法?
uj5u.com熱心網友回復:
試試這個(Python 3.9 用于|字典合并操作) :
dict1 = {"I"/span>: 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'/span>: 1, 'like': 1, ' potatoes': 1, 'tomatoes': 0}。
{'I': 1, 'like': 1, ' potatoes': 0, 'tomatoes': 1}。
uj5u.com熱心網友回復:
在 [14]: dict1= {"I": 1, "like":1," potatoes":1}。
...: dict2= {"I": 1, "like":1," tomatoes":1}。
在 [15]: keys1 = dict1.keys() # dict keys are set-like: https://docs.python.org/3/library/stdtypes.html#dict-views
在 [16]: keys2 = dict2.keys() # get keys of dict2 in another set()/span>
在 [17]: dict1.update(dict.fromkeys(keys2 - keys1, 0) # 從dict1中的專案和 "dict2中但不在dict1中的鍵 "建立結果,值為0。
在[18]: dict1
Out[18]: {'I'/span>: 1, 'like': 1, ' potatoes': 1, 'tomatoes': 0}。
在 [19]: dict2.update(dict.fromkeys(keys1 - keys2, 0) # 此處相同。
在[20]: dict2
Out[20]: {'I'/span>: 1, 'like': 1, 'tomatoes': 1, 'potatoes': 0}。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/311648.html
標籤:
上一篇:Pandas:匯入有多個作業表的xlsx,在每個df中添加列,并標明其所屬作業表的名稱,將有相同列數的df連接起來。
