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

Question:

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)

Asked By: CharlieDeBeadle

||

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.

Answered By: mgilson

In python version >3.6 you can use the sorted() function for sorting a dictionary

The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal

Refer Python Docs

Answered By: Raj

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)]
Answered By: Amir194
sorted(dictionary.items(), key=lambda x: (x[1] * -1, x[0]))  

the above answer will work for the below test case

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)
Answered By: Madhubabu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.