Filter out elements that occur less times than a minimum threshold

Satish Bandaru picture Satish Bandaru · Jun 24, 2017 · Viewed 9.8k times · Source

After trying to count the occurrences of an element in a list using the below code

from collections import Counter
A = ['a','a','a','b','c','b','c','b','a']
A = Counter(A)
min_threshold = 3

After calling Counter on A above, a counter object like this is formed:

>>> A
Counter({'a': 4, 'b': 3, 'c': 2})

From here, how do I filter only 'a' and 'b' using minimum threshold value of 3?

Answer

cs95 picture cs95 · Jun 24, 2017

Build your Counter, then use a dict comprehension as a second, filtering step.

{x: count for x, count in A.items() if count >= min_threshold}
# {'a': 4, 'b': 3}