Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering a dictionary by value AND key in Python?

I have the following dictionary:

dic = {'s': 3, 'a': 2, 'w': 2, 'y': 2, 'x': 2, 'm': 4, 'd': 5}

And I need to order the elements first by VALUE, and in case the values are repeated, then sort by KEY, so I would get the following output:

dic = [('d', 5), ('m', 4), ('s', 3), ('a', 2), ('w', 2), ('x', 2), ('y', 2)]

I have tried using this code:

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

But I keep getting the same output (the letters whose key is equal to 2 are not alphabetically ordered):

[('d', 5), ('m', 4), ('s', 3), ('a', 2), ('w', 2), ('y', 2), ('x', 2)]

Does anyone know how I can solve this problem?

Thanks in advance.

like image 806
Caroline Avatar asked Sep 12 '25 07:09

Caroline


2 Answers

You can sort the dict items with a key function that returns a 2-tuple with a negated value of the dict item as the first item, and the key as the second item:

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

This returns:

[('d', 5), ('m', 4), ('s', 3), ('a', 2), ('w', 2), ('x', 2), ('y', 2)]
like image 107
blhsing Avatar answered Sep 14 '25 21:09

blhsing


You were almost there, you need to include both the key and value in your lambda sort:

sorted(dic.items(), key=lambda x: (-x[1],x[0]))
like image 41
d_kennetz Avatar answered Sep 14 '25 19:09

d_kennetz