Home > front end >  How do I sort a dictionary by key ascending & value descending?
How do I sort a dictionary by key ascending & value descending?

Time:03-01

I'd like to sort dictionary like below:

from

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

to

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?

CodePudding user response:

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.

  • Related