Sort dictionary by multiple values

I have a dictionary {'Bill': 4, 'Alex' : 4, 'Bob' : 3, "Charles": 7}

I need to sort this dictionary first numerically, then inside it, in alphabetical order. If 2 elements have the same key number, they must be sorted in alphabetical order.

The result of this should be Bob, Alex, Bill, Charles

I tried using lambda, list comprehension, etc., but I can't get them to sort correctly.

+6
source share
2 answers

Using sorted with a key function (first in order ( d[k] ), then k ):

 >>> d = {'Bill': 4, 'Alex' : 4, 'Bob' : 3, "Charles": 7} >>> sorted(d, key=lambda k: (d[k], k)) ['Bob', 'Alex', 'Bill', 'Charles'] 
+11
source

Sort by dictionary elements (which are tuples) using sorted() . You can specify the sort key, which will have the values โ€‹โ€‹of the dictionary, and then its keys:

 >>> d = {'Bill': 4, 'Alex' : 4, 'Bob' : 3, "Charles": 7} >>> sorted(d.items(), key=lambda x:(x[1],x[0])) [('Bob', 3), ('Alex', 4), ('Bill', 4), ('Charles', 7)] >>> [t[0] for t in sorted(d.items(), key=lambda x:(x[1],x[0]))] ['Bob', 'Alex', 'Bill', 'Charles'] 
+4
source

All Articles