How to sort this dictionary? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to sort this dictionary?

I need to sort this dictionary in this program by values but it is not working. https://code.sololearn.com/coMZ7ek4kBvO/?ref=app

19th Jun 2020, 11:21 AM
Mohammad Ansah Kuriyodath
Mohammad Ansah Kuriyodath - avatar
3 Answers
+ 6
A dict can be sorted by using a dict comprehension like this: am={"a":2,"b":1,"c":3} print({key: value for key, value in sorted(am.items(), key=lambda x: x[1],reverse=True)}) #output is {'c': 3, 'a': 2, 'b': 1}
19th Jun 2020, 3:24 PM
Lothar
Lothar - avatar
+ 3
You can not directly sort a dictionary, you can only create a new dictionary from a sorted iterable. print( { x: dict[x] for x in sorted( dict, key=lambda x: dict[x], reverse=True ) } )
19th Jun 2020, 11:56 AM
HonFu
HonFu - avatar
+ 2
Since it's probably not needed to reshape the whole dict if it's only for output, I would btw probably do something like this: width = len( max(dict, key=lambda x: len(x)) ) for key in sorted( dict, key = lambda x: dict[x], reverse = True ): print(key.ljust(width), dict[key])
19th Jun 2020, 3:37 PM
HonFu
HonFu - avatar