Default dictionary

So far we have learned about regular dictionary and ordered dictionary. In this section, we will learn a special type of dictionary called default dictionary, which is provided by the defaultdict module of collections. A defaultdict works exactly the way a normal dict does, but it is initialized with a callable function called default_factory() that takes no arguments and provides a default value for a nonexistent key.

Syntax

defaultdict(default_factory())

We will try to understand with two examples:

from collections import defaultdict

def func():
return "Cricket"

game = defaultdict(func)

game["A"]= "Football"
game["B"] = "Badminton"

print game
print game["A"]
print game["B"]
print game["C"]

In this case, our function or function func acts as a default_factory function. We have assigned game["A"]= "Football", where  "A" is the key. If key is new (not found in the dictionary "game"), then defaultdict does not give an error; instead, it returns the default value, which is returned by the default_factory() function. So, for the new key "C", the default value is "Cricket". This will be more clear with the mentioned output:

The preceding task can be achieved by following the lambda function. Let's understand with an example:

from collections import defaultdict
game = defaultdict(lambda : "Cricket")

game["A"]= "Football"
game["B"] = "Badminton"

print game
print game["A"]
print game["B"]
print game["C"]

Here, we just used the lambda function, which initializes the default value of "Cricket" if any new key is encountered:

Now, next we will use int as default_factory function. The default value for int is 0:

from collections import defaultdict

game = defaultdict(int)

game["A"]= "Football"
game["B"] = "Badminton"

print game
print game["A"]
print game["B"]
print game["C"]

Here, we just initialized the int value for any new key encountered. For game["C"], the output returned is 0:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.141.219