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

How to sort dictionary? In python.

Help me

2nd Jan 2021, 2:57 AM
Rathindhar .R.M
Rathindhar .R.M - avatar
3 Answers
+ 8
Here are some examples. https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value https://www.geeksforgeeks.org/JUMP_LINK__&&__python__&&__JUMP_LINK-sort-python-dictionaries-by-key-or-value/ - - - - - - - - - - - - - - - - - Just a quick example: x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} x = {k: v for k, v in sorted(x.items(), key=lambda item: item[0])} print(x) >> {0: 0, 1: 2, 2: 1, 3: 4, 4: 3} # sorted by key - - - - - - - - - - - - - - - - - -- x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} x = {k: v for k, v in sorted(x.items(), key=lambda item: item[1])} print(x) >> {0: 0, 2: 1, 1: 2, 4: 3, 3: 4} #sorted by value
2nd Jan 2021, 3:02 AM
noteve
noteve - avatar
2nd Jan 2021, 3:03 AM
Dino Wun (Use the search bar plz!)
Dino Wun (Use the search bar plz!) - avatar
2nd Jan 2021, 3:09 AM
Rathindhar .R.M
Rathindhar .R.M - avatar