Search code examples
pythonpython-3.xcounterpython-itertools

Get all elements with count less than 50 from a counter


Code

from itertools import dropwhile
for key, count in dropwhile(lambda key_count: key_count[1] < 50, countered.most_common()):
    del countered[key]

Input which is the countered variable looks like this

[('Required Weather API', 100),
 ('New York City Museums', 70),
 ('New York City Art Galleries', 48),
 ('Zillow Home Value Searching API', 38)]

I used the code above to get the items with count less than 50 into a list but I get an empty counter back Counter()

Expected output

[('New York City Art Galleries', 48),
 ('Zillow Home Value Searching API', 38)]

Thanks


Solution

  • That seems complicated. Why not use:

    res = [item for item in countered if item[1]<50]
    

    gives

    [('New York City Art Galleries', 48), ('Zillow Home Value Searching API', 38)]