![](/img/trans.png)
[英]How to combine two dictionaries? One dict as key, another dict as value
[英]Compare two dictionaries, remove key/value pair in one dict if it exists in the other
我有兩本詞典。 一個看起來像這樣:
dict1 = {'ana': 'http://ted.com', 'louise': 'http://reddit.com', 'sarah':'http://time.com'}
另一個看起來像這樣:
dict2 = {'patricia': 'http://yahoo.com', 'ana': 'http://ted.com',
'louise': 'http://reddit.com', 'florence': 'http://white.com'}
我需要比較兩個字典,並從dict2
中dict1
已存在於dict1
任何鍵/值對
正如你所看到的,安娜和路易絲已經存在於dict1
,所以我想從自動刪除dict2
預計將包含獨有的唯一要素的輸出dict2
,而不是已經存在於dict1
,和看起來像:
dict2 = {'patricia': 'http://yahoo.com', 'florence': 'http://white.com'}
關於Sarah在dict1
我不需要做任何事情。 我只關心將dict2
與dict1
進行比較以刪除重復項。
額外信息:
我試圖以許多不同的方式遍歷dicts,但它給了我兩種類型的錯誤: dict content changed during action
not hashable type
dict content changed during action
not hashable type
或dict content changed during action
。
我還嘗試將每個列表組合並組合列表,但最終結果是另一個列表,我不知道如何將列表轉換回字典。
如果密鑰匹配, Jim的答案將刪除項目。 如果鍵和值都匹配,我想你想要刪除。 這實際上非常簡單,因為您使用的是Python 3:
>>> dict(dict2.items() - dict1.items())
{'florence': 'http://white.com', 'patricia': 'http://yahoo.com'}
它的工作原理是因為dict_items
對象將減法操作視為設置差異。
如果你們中的任何人正在尋找python 2.x的解決方案(因為我一直在尋找),那么這就是答案:
dict(filter(lambda x: x not in dict2.items(), dict1.items()))
然后只使用字典理解:
dict2 = {i:j for i,j in dict2.items() if i not in dict1}
這導致dict2
是:
{'florence': 'http://white.com', 'patricia': 'http://yahoo.com'}
就地解決方案可以是:
for k in dict1:
dict2.pop(k, None)
產生類似的結果。
這只是查找dict1中dict2中的所有鍵,然后從dict2中刪除鍵/值對。
for key in dict1:
if key in dict2 and (dict1[key] == dict2[key]):
del dict2[key]
鋤頭有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.