21
votes

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

I need to sort this dictionary first numerically, then within that, alphabetically. If 2 items have the same number key, they need to be sorted alphabetically.

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

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

2

2 Answers

36
votes

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

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

Sort on the dictionary's items (which are tuples) using sorted(). You can specify the sort key which will be by the dictionary's values, 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']