Up to this level of Python, you have learned data structure of Python.
module of Python includes implementations of several data structures
that extend those found in other modules. Gradually you will learn the power of collections module.
Let us discuss its power one by one.
Python Collections OrderedDict
Python OrderedDict is a dictionary subclass that remembers the order in which its contents
d1 = collections.OrderedDict()
d1 is ordered dictionary here.
Let us discuss the comparison between regular Python dictionary and Python ordered dictionary.
You can see that order dictionary is retaining their order in which contents are added.
sorted of order dictionary based upon key
dict = collections.OrderedDict(sorted(d1.items()))
= New sorted dictionary
= Original Order dictionary
By default dictionary is sorted according to key.
sorted of order dictionary based upon values
dict = collections.OrderedDict(sorted(d1.items(), key=lambda (k,v): v))
= New sorted Python dictionary
= Original Order Python dictionary
The above lambda function change the key to its value. Because ordered dict is return (key, value) pair. Lambda function make key = value, Thus
ordered dictionary will be sorted by its value.
lambda function is explained in special function section.