简体   繁体   中英

Compare two collections.defaultdict and remove similar values

I have two collections.defaultdict and trying to remove values from d1 that are also in d2 .

from collections import Counter, defaultdict
d1 = Counter({'hi': 22, 'bye': 55, 'ok': 33})
d2 = Counter({'hi': 10, 'hello': 233, 'nvm': 96})

Ideal result:

d3 = set()
d3 = ({'bye':55, 'ok':33})

So far I have tried:

d3 = set()
d3 = d1 - d2
print(d3)
Counter({'bye': 55, 'ok': 33, 'hi': 12}) 

But this keeps the same value of 'hi' even though I want to remove all similar ones.

Since, d1 and d2 are Counter objects they implement subtraction different than sets.

From collections.Counter (emphasis mine):

Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements .

From set.difference or set - other :

Return a new set with elements in the set that are not in the others.

That said, you can use Counter.keys and use difference just like sets.

keys = d1.keys() - d2.keys()
# keys = {'bye', 'ok'}

out = {k: d1[k] for k in keys}
# out = {'bye': 55, 'ok': 33}

Use a dictionary comprehension

d3 = {k: v for k, v in d1.items() if k not in d2}
print(d3)

Result:

{'bye': 55, 'ok': 33}

trying to remove values from d1 that are also in d2

for k in d2:
    d1.pop(k, None)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM