Python Collections
Up to this level of Python, you have learned data structure of Python.
Python
collections 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
are added.
Syntax
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
Syntax
dict = collections.OrderedDict(sorted(d1.items()))
dict = New sorted dictionary
d1= Original Order dictionary
By default dictionary is sorted according to key.
sorted of order dictionary based upon values
Syntax
dict = collections.OrderedDict(sorted(d1.items(), key=lambda (k,v): v))
dict = New sorted Python dictionary
d1= 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.