DefaultDict objects can be initialized using DefaultDict() method by passing the data type as an argument.
Example script :
# 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)
Then Output :
defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})
Source : https://www.geeksforgeeks.org/python-collections-module/
No comments:
Post a Comment