简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM