import collections import operator def compare(x, y): if x[1] > y[1]: return 1 elif x[1] < y[1]: return -1 elif x[1] == y[1]: if x > y: return 1 elif x < y: return -1 return 0 document = "Practice makes perfect, you'll get perfecT by practice. just practice! just just just!!" words = document.split() d = collections.defaultdict(int) for word in words: word = word.lower() word = [c if c >= 'a' and c <= 'z' else "" for c in word] word = "".join(word) d[word] += 1 output = [] d = sorted(d.items(), cmp=compare, reverse=True) print(d) #getting: [('just', 4), ('practice', 3), ('perfect', 2), ('youll', 1), ('makes', 1), ('get', 1), ('by', 1)] #expected: [["just","4"],["practice","3"],["perfect","2"],["makes","1"],["youll","1"],["get","1"],["by","1"]]