How to use int as default_factory In Python

When the int class is passed as the default_factory argument, then a defaultdict is created with default value as zero.
Example:

Python3




# Python program to demonstrate
# defaultdict
   
   
from collections import defaultdict
   
   
# Defining the dict
d = defaultdict(int)
   
L = [1, 2, 3, 4, 2, 4, 1, 2]
   
# Iterate through the list
# for keeping the count
for i in L:
       
    # The default value is 0
    # so there is no need to 
    # enter the key first
    d[i] += 1
       
print(d)


Output:

defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})


Defaultdict in Python

Dictionary in Python is an unordered collection of data values that are used to store data values like a map. Unlike other Data Types that hold only single value as an element, the Dictionary holds key-value pair. In Dictionary, the key must be unique and immutable. This means that a Python Tuple can be a key whereas a Python List can not. A Dictionary can be created by placing a sequence of elements within curly {} braces, separated by ‘comma’.

Example:

Python3




# Python program to demonstrate
# dictionary
  
  
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'
print("Dictionary:"
print(Dict)
print(Dict[1])
  
# Uncommenting this print(Dict[4])
# will raise a KeyError as the
# 4 is not present in the dictionary


Output:

Dictionary:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Geeks
Traceback (most recent call last):
  File "/home/1ca83108cc81344dc7137900693ced08.py", line 11, in 
    print(Dict[4])
KeyError: 4

Sometimes, when the KeyError is raised, it might become a problem. To overcome this Python introduces another dictionary like container known as Defaultdict which is present inside the collections module.
Note: For more information, refer to Python Dictionary.
 

Similar Reads

DefaultDict

...

Inner Working of defaultdict

Defaultdict is a container like dictionaries present in the module collections. Defaultdict is a sub-class of the dictionary class that returns a dictionary-like object. The functionality of both dictionaries and defaultdict are almost same except for the fact that defaultdict never raises a KeyError. It provides a default value for the key that does not exists....

Using List as default_factory

...

Using int as default_factory

Defaultdict adds one writable instance variable and one method in addition to the standard dictionary operations. The instance variable is the default_factory parameter and the method provided is __missing__....