May 2017
Intermediate to advanced
280 pages
6h 2m
English
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 ...
Read now
Unlock full access