![](/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.