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

Time:06-20

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

CodePudding user response:

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}
  • Related