Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort Dictionary Python

I have a dictionary for example like {"abc": 3, "dcb": 4, "dab": 4, "dfb": 5}.
I would like to sort it by value and by keys, where the value is more important than the key.
So in our example we would get:

{"dfb" : 5, "dab" : 4, "dcb" : 4, "abc" : 3}

More preferably if it is presented as a list rather than dictionary.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could use sorted on the dictionary items with the reversed order as key to make the value the major key, and negative value for descending order:

sorted(d.items(), key=lambda x: (-x[1], x[0]))

Output:

[('dfb', 5), ('dab', 4), ('dcb', 4), ('abc', 3)]

NB. the exact expected output is unclear but you can easily convert to dictionary or list of lists from there

dict(sorted(d.items(), key=lambda x: (-x[1], x[0])))
# {'dfb': 5, 'dab': 4, 'dcb': 4, 'abc': 3}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading