Sorting of ordered dictionary based upon values

We can also sort the ordered dictionary based upon values:

Syntax

 dict = collections.OrderedDict(sorted(d1.items(), key=lambda (k,v): v)) 
dict = New sorted dictionary
d1= Original Ordered dictionary

Here, the lambda function changes the key to its value. As ordered, the dictionary returns the (key, value) pair. The lambda function makes key = value, thus the ordered dictionary will be sorted by its value. Let's take an example to understand the sorting of the ordered dictionary based upon values:

import collections 
print 'n Order dictionary'
d1 = collections.OrderedDict()
d1['a']= 'SAS'
d1['d']= 'PYTHON'
d1['b']= 'SAP HANNA'
d1['f']= 'R'
d1['c']= 'JULIA'

for k,v in d1.items():
print k, ":",v
print 'n Sorted Order dictionary'
dict = collections.OrderedDict(sorted(d1.items(), key=lambda (k,v): v))

for k,v in dict.items():
print k, ":",v

As you can clearly see from the preceding example, the lambda() function converts key to value and we can see the output as shown here:

The lambda function is explained in the special function section.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.148.104.124