Python Sorting Dictionary

A lambda is a function that does not have a name. Lambda functions are written using a single statement and hence look like expressions. Lambda functions are written without using 'def' keyword. They are useful to perform some calculations or processing easily.


Operations on Dictionaries

Here, color code and its name are given as key-value pairs. Suppose we want to sort this dictionary into ascending order of keys, i.e. on color codes, we can use sorted() function in the following format:

sorted(elements, key = color code)

Here, elements of the dictionary can be accessed using the colors.items() method. A key can be prescribed using a lambda function as:

key = lambda t: t[0]

The sorted() function can be written as:

sorted(colors.items(), key = lambda t: t[0])

sorted(colors.items(), key = lambda t: t[0])

This will sort all the elements of the dictionary by taking color code (indicated by t[0]) as the key. If we want to sort the dictionary based on color name, then we can write:

sorted(colors.items(), key = lambda t: t[1])

This will sort the elements of the dictionary by taking color name (indicated by t[1]) as the key.


A Python program to sort the elements of a dictionary based on a key or value.