[英]Compare two dictionaries, remove key/value pair in one dict if it exists in the other
I have two dictionaries. 我有两本词典。 One looks like this:
一个看起来像这样:
dict1 = {'ana': 'http://ted.com', 'louise': 'http://reddit.com', 'sarah':'http://time.com'}
The other one looks like this: 另一个看起来像这样:
dict2 = {'patricia': 'http://yahoo.com', 'ana': 'http://ted.com',
'louise': 'http://reddit.com', 'florence': 'http://white.com'}
I need to compare the two dictionaries, and eliminate from dict2
any key/value pair already present in dict1
我需要比较两个字典,并从
dict2
中dict1
已存在于dict1
任何键/值对
As you can see, Ana and Louise already exist in dict1
, so I'd like to automatically delete it from dict2
The output expected would contain only elements unique to dict2
and not already present in dict1
, and would look like: 正如你所看到的,安娜和路易丝已经存在于
dict1
,所以我想从自动删除dict2
预计将包含独有的唯一要素的输出dict2
,而不是已经存在于dict1
,和看起来像:
dict2 = {'patricia': 'http://yahoo.com', 'florence': 'http://white.com'}
I don't need to do anything about Sarah being in dict1
. 关于Sarah在
dict1
我不需要做任何事情。 I only care about comparing dict2
with dict1
to remove duplicates. 我只关心将
dict2
与dict1
进行比较以删除重复项。
Extra info: 额外信息:
I tried to loop over the dicts in many different ways but it gave me two types of errors: not hashable type
or dict content changed during action
. 我试图以许多不同的方式遍历dicts,但它给了我两种类型的错误:
dict content changed during action
not hashable type
dict content changed during action
not hashable type
或dict content changed during action
。
I also tried to make each into a list and combine the lists, but the end result is another list and I don't know how to turn a list back into a dictionary. 我还尝试将每个列表组合并组合列表,但最终结果是另一个列表,我不知道如何将列表转换回字典。
Jim's answer removes items if the keys match. 如果密钥匹配, Jim的答案将删除项目。 I think you wanted to remove if both key and value matched.
如果键和值都匹配,我想你想要删除。 This is actually very easy since you're using Python 3:
这实际上非常简单,因为您使用的是Python 3:
>>> dict(dict2.items() - dict1.items())
{'florence': 'http://white.com', 'patricia': 'http://yahoo.com'}
It works because dict_items
objects treat subtraction operations as set differences. 它的工作原理是因为
dict_items
对象将减法操作视为设置差异。
如果你们中的任何人正在寻找python 2.x的解决方案(因为我一直在寻找),那么这就是答案:
dict(filter(lambda x: x not in dict2.items(), dict1.items()))
Then just use a dictionary comprehension: 然后只使用字典理解:
dict2 = {i:j for i,j in dict2.items() if i not in dict1}
which results in dict2
being: 这导致
dict2
是:
{'florence': 'http://white.com', 'patricia': 'http://yahoo.com'}
An in-place solution could be: 就地解决方案可以是:
for k in dict1:
dict2.pop(k, None)
which yields a similar result. 产生类似的结果。
This simply looks for all the keys in dict1 that are in dict2 and then deletes the key/value pairs from dict2. 这只是查找dict1中dict2中的所有键,然后从dict2中删除键/值对。
for key in dict1:
if key in dict2 and (dict1[key] == dict2[key]):
del dict2[key]
Hoe this helps! 锄头有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.