Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting dictionary keys by value, then those with the same value alphabetically

I know it wasn't well explained in the title so I'll try and do a better job here. I want to sort a dictionary's keys by their respective values, and then sort any keys with the same value alphabetically. What is the best way to do this, ideally without the use of modules?

Does python do this automatically with a sort like:

sorted(dictionary.items(), key=lambda x: x[1])

I tried the above code and it seemed to work but I couldn't tell if it was just coincidence or not. I couldn't find anything in the docs and I need to know if it will always work.

Starting dictionary:

dictionary = {'d':2, 'c':1, 'a':2, 'b':3}

Sorted by value:

['c', 'd', 'a', 'b']

(1, 2, 2, 3)

Items with the same value sorted alphabetically:

['c', 'a', 'd', 'b']

(1, 2, 2, 3)

like image 251
CharlieDeBeadle Avatar asked Feb 06 '15 00:02

CharlieDeBeadle


2 Answers

I think that you want:

sorted(dictionary.items(), key=lambda t: t[::-1])

which is the same as:

def reverse_tuple(t):
    return t[::-1]

sorted(dictionary.items(), key=reverse_tuple)

This works because tuples are sorted lexicographically. The first element is compared, if those are equal, python moves on to the second and so forth.

This is almost just sorted(dictionary.items()) unfortunately, then your primary sort order is determined by the first element in the tuples (i.e. the key) which isn't what you want. The trick is to just reverse the tuples and then the comparison works as you want it to.

like image 140
mgilson Avatar answered Nov 16 '22 07:11

mgilson


This will do the trick:

sorted(dic.items(),key= lambda  x: (x[1],x[0]))

It will be sorted in ascending order based on the second element(value of dictionary). If values of the dictionary are equal it will compare the first elements and sort them alphabetically. A better example to show this:

dic = {'abc':3, 'x':1, 'bcc':4, 'a':6 , 'bba':4  , 'bg':4 }

sorted:

[('x', 1), ('abc', 3), ('bba', 4), ('bcc', 4), ('bg', 4), ('a', 6)]
like image 1
Amir194 Avatar answered Nov 16 '22 09:11

Amir194