Search code examples
pythoncounter

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.


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.