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 Default Dictionary

You have learned Regular dictionary and Ordered Dictionary, In this section you will learn a special type of dictionary called default dictionary provided by defaultdict module of collections. A defaultdict works exactly like a normal dict, but it is initialized with a callable function called default_factory that takes no arguments and provides the default value for a nonexistent key. We will see different-2 example to learn the defaultdict.

Example 1 default_factory as function

Python collection default dictionary
Python default dictionary
Click to view code
You can see that default_factory is a function which is defined earlier, don't use func() use only name like func. So what is default value of dictionary game. By using game["Bhaskar"]= "Football" we have defined value "Football" on "bhaskar" key. If key is new (not found in dictionary "game") then defaultdict does not give error, it will return the default value which is returned by default_factory function. So for new key "Mohit", default value is "Cricket".
The above task can be achieved by following lambda function.
Python collection defaultdict
Python default dictionary
Click to view code

Example 2 default_factory as int

This time we will use int as default_factory. Default value of int is 0.
default dictionary with int
Python default dictionary with int
Click to view code
So game["Mohit"] is 0.
Consider a simple problem solved by Default dictionary, You want to calculate the frequency of values of list. Let us see next code.
default dictionary with int with list
Python default dictionary with int with list
Click to view code
You know default value is 0. We incremented it by 1. In this way you can calculate the frequency of value of list.

Example 3 default_factory as list

Consider a real problem, you have list of tuples pair. Like
list_state = [('Haryana', 'Yamunanagar'), ('Haryana', 'Ambala'), ('Haryana', 'karnal'), ('Punjab', 'patiala'), ('Punjab', 'Chandigarh'), ('UP', 'Noida')]
The above list is the pair of (State , district). So our aim to make state as key and district as list of values.
See the below code.
default dictionary with  list
Python default dictionary with list
Click to view code
Default value is list here, First value of tuple is fixed as key and second value is appended.






admin