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.
f = lambda x, y: x+y
colors = {10: "Red", 35: "Green", 15: "Blue", 25: "White"}
Sort 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.
colors = {10: "Red", 35: "Green", 15: "Blue", 25: "White"}
c1 = sorted(colors.items(), key = lambda t: t[0])
print(c1)
c1 = sorted(colors.items(), key = lambda t: t[0],reverse=True)
print(c1)
c2 = sorted(colors.items(), key = lambda t: t[1])
print(c2)
c2 = sorted(colors.items(), key = lambda t: t[1],reverse=True)
print(c2)