[Tutor] sort by value and then by key

Alan Gauld alan.gauld at yahoo.co.uk
Sun Dec 24 03:48:50 EST 2017


On 24/12/17 08:12, anish singh wrote:

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

Define "not working"
Do you get an error message? (show us)
If the output different to what you expect (show us)

Have you tried printing the intermediate results?
For example the dictionary before you sort it?
Or what about using the default sort, how close is that?

Don't expect us to run your code and check the output.
You've already done that so share the information.

> ----------------------------------------------------------------------------------------
> 
> 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)
> -----------------------------------------------------------------

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list