[Tutor] sort by value and then by key

anish singh anish198519851985 at gmail.com
Sun Dec 24 03:12:15 EST 2017


document = "Practice makes perfect. you'll only get
                     Perfect by practice. just practice!"

output: [ ["practice", "3"], ["perfect", "2"], ["by", "1"],
              ["get", "1"], ["just", "1"], ["makes", "1"],
              ["only", "1"], ["youll", "1"] ]

I am supposed to return a list of all unique words
in it and their number of occurrences, sorted by
the number of occurrences in a descending order.
If two or more words have the same count, they
should be sorted alphabetically (in an ascending order).

However, I am stuck. I have below code which is not working.

----------------------------------------------------------------------------------------

import collections

x = collections.OrderedDict()
import collections
import operator


def make_comparator(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 only get Perfect by
practice. just practice!"
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 = []
for key, value in sorted(d, cmp = make_comparator(x)):
    output.append([key, value])
print(output)
----------------------------------------------------------------------------------------

Thanks,


More information about the Tutor mailing list