Search code examples
pythonlistloopsfor-loopfor-in-loop

Python list of frequent occurrences in a list of strings


I'm writing a python function that consumes a list of strings and produces a list of the most frequently occurring items.

For example:

>>> trending(["banana", "trouble", "StarWars", "StarWars", "banana", "chicken", "BANANA"])
["banana", "StarWars"]

but

>>> trending(["banana", "trouble", "StarWars", "Starwars", "banana", "chicken"])
["banana"]

So far, I've written a function that produces only the first word that appears frequently instead of a list of words that appear frequently. Also, my list contains the index of that one frequent item.

def trending(slst):
    words = {}
    for word in slst:
        if word not in words:
            words[word] = 0
        words[word] += 1
    return words

How can I fix this function to produce a list of the most frequently occurring items (instead of the first of the most frequently occurring items) and how do I remove the index?


Solution

  • Without the use of Counter you can make your own counter with a dict and extract frequent items:

    def trending(slst):
        count = {}
        items = []
    
        for item in set(slst):
            count[item] = slst.count(item)
    
        for k, v in count.items():
            if v == max(count.values()):
                items.append(k)
    
        return items