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
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:
dict2 = {'patricia': 'http://yahoo.com', 'florence': 'http://white.com'}
I don't need to do anything about Sarah being in dict1
. I only care about comparing dict2
with dict1
to remove duplicates.
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
.
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. I think you wanted to remove if both key and value matched. This is actually very easy since you're using 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.
如果你们中的任何人正在寻找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:
{'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.
for key in dict1:
if key in dict2 and (dict1[key] == dict2[key]):
del dict2[key]
Hoe this helps!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.