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 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
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
Example 2 default_factory as int
This time we will use int
as default_factory. Default value of int
Consider a simple problem solved by Default dictionary, You want to calculate the frequency of values of list.
Let us see next 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 value is list here, First value of tuple is fixed as key and second value is appended.