Sorting Python dictonary

Python has quite a nice mechanism for sorting. Here is an example to sort a list of integers.

a = [1, 5, 11, 6, 7, 2, 10, 4]
a = sorted(a)
print(a)

Result

[1, 2, 4, 5, 6, 7, 10, 11]

This is really easy but sorting a dictionary by key is a little more complicated. Here is an example.

data = {1: 'e', 5: 'a', 3: 'b', 2: 'c', 4: 'd'}
sorted_data = sorted(data.items(), key=lambda item: item[0])

for k, v in sorted_data.items():
    print(f"{k}: {v}")

Result

1: e
2: c
3: b
4: d
5: a

Now let’s try to sort by value.

data = {1: 'e', 5: 'a', 3: 'b', 2: 'c', 4: 'd'}
sorted_data = sorted(data.items(), key=lambda item: item[1])

for k, v in sorted_data:
    print(f"{k}: {v}")

Result

5: a
3: b
2: c
4: d
1: e

It uses lambda. This means this method could be used for different types of object. In my next blog, I will talk about anonymous type of object in Python and sorting list of objects.

Author: admin

A software engineer in greater Seattle area

Leave a Reply

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