Sorting a `dictionary` in python

Many people think that sorting is not possible for dictionary, because they are not able to find a `.sort()` as in list for dictionary. Actually there is a function called `sorted()` which can be used to sort dictionary based on keys as well as values. Check the official python documentation for more details.

#! /usr/bin/python

a = {'one': 1, 'three': 3, 'four': 4, 'two': 2}
sorted(a.items(), key=lambda x: x[1])

# output [('one', 1), ('two', 2), ('three', 3), ('four', 4)]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s