Linux

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.
Difference between Python Regular and Python orderedDict
Python Order dictionary
Click to view code
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
Python OrderedDict sorted by key
Sorted Python dictionary by key
Click to view code
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.
Python OrderedDict sorted by value
Sorted dictionary by value
Click to view code
lambda function is explained in special function section.





admin