简体   繁体   中英

Firstly sort dictonary by values and if values are the same to sort in alphabetic order

I've got dictionary with {'text' : number}. Firstly, I need to sort dictionary by values and if values are the same to sort in alphabetical order. How to implement this?

Input:

dict = {"aaa" : 12, "ccc" : 13, "bbb" : 13, "ddd" : 11}

Output:

# ddd(11)  aaa(12)  ccc(13)  bbb(13)  -> sorting only by values

# ddd(11)  aaa(12)  bbb(13)  ccc(13) -> sorting second time also by alphabet, final result

You could use sorted :

>>> d = {'aaa' : 12, 'ccc' : 13, 'bbb' : 13, 'ddd' : 11}
>>> dict(sorted(d.items(), key=lambda t: (t[1], t[0]))) # Sort by value then by key.
{'ddd': 11, 'aaa': 12, 'bbb': 13, 'ccc': 13}

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