remove entry in counter object if value meets condition

Question:

Is there a way to remove entries from a counter object if the value matches a certain condition. For example:

Counter({'a': 1142,'b':1004,'c':100,'d':5})

I want to drop all indexes where it is less than 1000, so I just have ‘a’ and ‘b’ left. I know I can loop through each and then delete if it doesnt match the condition as shown in this solution. Just looking for a more efficient way.

Asked By: Nikita Belooussov

||

Answers:

You can use a simple loop to delete the keys in place:

from collections import Counter

c = Counter({'a': 1142,'b':1004,'c':100,'d':5})

for k in list(c):
    if c[k] < 1000:
        del c[k]

print(c)

Output:

Counter({'a': 1142, 'b': 1004})

If you want a copy:

c2 = Counter({k:v for k,v in c.items() if v>= 1000})
Answered By: mozway

I think it can be useful for you:

from collections import Counter
counter = Counter({'a': 1142, 'b': 1004, 'c': 100, 'd':5})
Counter({k: c for k, c in counter.items() if c >= 1000})

Output:

Counter({'a':1142 , 'b': 1004})

This way is more effective as you mentioned.

Answered By: Amirhossein Sefati
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.