0

So i have a list of strings like this:

mylist = ['foo', 'bar', 'foo', 'bar', 'abc']

and i want to have output like this:

foo exists twice
bar exists twice
abc exists once

I've tried converting the list to a dictionary with the string as the key and the value gets incremented for every occurrence in the list. But I'm not able to sort the dictionary in a way that i can print the most strings with the most occurrences along with the word. I've also tried using a 2 dimensional arrays which didn't work either. Does anyone know a good way of doing this?

David
  • 15
  • 1
  • 3

1 Answers1

1

You could use a dict or a default_dict and sort by values, but there's no need to reinvent the wheel. You need a Counter:

from collections import Counter
counter = Counter(['foo', 'bar', 'foo', 'bar', 'abc'])
print(counter.most_common())
# [('foo', 2), ('bar', 2), ('abc', 1)]

for (word, occurences) in counter.most_common():
    print("%s appears %d times" % (word, occurences))
# foo appears 2 times
# bar appears 2 times
# abc appears 1 times
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124