I am totally new to python and I already struggle with a fairly small task.
I have a wordlist, in which I want to count the (duplicate) words, show the top "n" words and in case of a tie, order them alphabetically.
For the first two parts I wrote this:
def count_words(s, n):
# TODO: Count the number of occurences of each word in s
wordlist = s.split()
counts = Counter(wordlist)
#Get top n words
top_n = counts.most_common(n)
print count_words("cat bat mat cat cat mat mat mat bat bat cat", 3)
[('mat', 4), ('cat', 4), ('bat', 3)]
[('cat', 4), ('mat', 4), ('bat', 3)]
top_n.sort(key=lambda x: (-x, x))
right before the return. It sorts by the first element of the key, then, if there's a tie, by the second. Since it sorts from smallest to biggest, the first value is multiplied by -1.