Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

remove entry in counter object if value meets condition

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading