Sort Python Dictionary by Key or Value for Beginners – Python Tips

By | August 2, 2019

To sort python dict, we will use sorted() function, in this tutorial, we will introduce how to sort.

Step 1. Create a dict

dic = {9:31, 4:5, 2:3, 1:4, 6:74, 5:0}

Step 2. Use sorted

dict= sorted(dic.items(), key=lambda d:d[1], reverse = True)

And the result is:

[(6, 74), (9, 31), (4, 5), (1, 4), (2, 3), (5, 0)]

Notice: d[0] means python sorts dictionary by key, d[1] means sorting by value.

If you use a string to keys, you can follow this code.

>>> dic = {'m':31, 'n':5, 'g':3, 't':4, 'b':74, 'a':0}
>>> dict= sorted(dic.items(), key=lambda d:d[1], reverse = True)
>>> dict
[('b', 74), ('m', 31), ('n', 5), ('t', 4), ('g', 3), ('a', 0)]

Leave a Reply

Your email address will not be published. Required fields are marked *