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.
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)]
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]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With