johnb johnb - 1 month ago 7
Python Question

How to do Sort the occurences in descending order (alphabetically in case of ties /in this program

>>> words=input('enter your sensence:')
enter your sensence:it was the best of times it was the worst of times it was the age of wisdom it was the age of foolishnes
>>> wordcount={}
>>> for word in words.split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1


>>> print(word, wordcount)
foolishnes {'age': 2, 'of': 4, 'it': 4, 'wisdom': 1, 'was': 4, 'the': 4, 'worst': 1, 'times': 2, 'foolishnes': 1, 'best': 1}

Answer

You already have your wordcounts. Here's how you would print them out in sorted order:

def printout(wordcount):
    for k in sorted(wordcount, key=lambda k: (wordcount[k], k)):
        print(k, wordcount[k])
Comments