比较两个 collections.defaultdict 并删除相似的值

Compare two collections.defaultdict and remove similar values

我有两个 collections.defaultdict 并试图从 d1 中删除也在 d2.

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

理想结果:

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

到目前为止我已经尝试过:

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

但是即使我想删除所有相似的值,这仍保持 'hi' 的相同值。

使用字典理解

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

结果:

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

因为 d1d2Counter 对象,它们实现的减法不同于集合。

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.

也就是说,您可以像集合一样使用 Counter.keysdifference

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

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

trying to remove values from d1 that are also in d2

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