简体   繁体   English

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

[英]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 .我有两个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})

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.但是即使我想删除所有类似的值,这也会保持'hi'的相同值。

Since, d1 and d2 are Counter objects they implement subtraction different than sets.由于d1d2Counter对象,因此它们实现的减法不同于集合。

From collections.Counter (emphasis mine):来自collections.Counter (强调我的):

Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements .加法和减法通过增加或减去相应元素的计数来组合计数器。

From set.difference or set - other :set.differenceset - 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.也就是说,您可以使用Counter.keys并像集合一样使用difference

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试图从d1中删除也在d2

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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