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

How do I sort a dictionary by key ascending & value descending?

I’d like to sort dictionary like below:

from

unsorted_list :  {'F': 3, 'A': 1, 'B': 2, 'C': 2, 'E': 2, 'D': 1,}

to

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

sorted_list :  {'D': 1, 'A': 1, 'E': 2, 'C': 2, 'B': 2, 'F': 3,}

So,

  1. sorting by value Ascending then,
  2. sorting by key Descending

How can I do this by python?

>Solution :

Dictionaries preserve order of insertion, so if you want to re-order them, you need to build a new dict where you insert the items in the desired order. You can do this pretty easily by sorting the dict’s items() and then passing the result to dict():

>>> d = {'F': 3, 'A': 1, 'B': 2, 'C': 2, 'E': 2, 'D': 1,}
>>> dict(sorted(d.items(), key=lambda i: (-i[1], i[0]), reverse=True))
{'D': 1, 'A': 1, 'E': 2, 'C': 2, 'B': 2, 'F': 3}

Note that if dictionary ordering is important to your use case, you might want to use an OrderedDict, which has more robust support for rearranging items in-place.

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