python中defaultdict
Defaultdict is a container like dictionaries present in the module collections. Defaultdict is a sub-class of the dict class that returns a dictionary-like object. The functionality of both dictionaries and defualtdict are almost same except for the fact that defualtdict never raises a KeyError. It provides a default value for the key that does not exists.
Syntax: defaultdict(default_factory)
Parameters:
- default_factory: A function returning the default value for the dictionary defined. If this argument is absent then the dictionary raises a
KeyError.
Example:
# Python program to demonstrate # defaultdict from collections import defaultdict # Function to return a default # values for keys that is not # present def def_value(): return "Not Present" # Defining the dict d = defaultdict(def_value) d["a"] = 1d["b"] = 2 print(d["a"]) print(d["b"]) print(d["c"]) |
Output:
1
2
Not Present
Using List as default_factory
When the list class is passed as the default_factory argument, then a defaultdict is created with the values that are list.
Example:
# Python program to demonstrate # defaultdict from collections import defaultdict # Defining a dict d = defaultdict(list) for i in range(5): d[i].append(i) print("Dictionary with values as list:") print(d) |
Output:
Dictionary with values as list:
defaultdict(<class 'list'>, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]})
Using int as default_factory
When the int class is passed as the default_factory argument, then a defaultdict is created with default value as zero.
Example:
# 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})
这个factory_function可以是list、set、str等等,当key不存在时,返回的是factory_function的默认值,比如list对应[ ],str对应的是空字符串,set对应set( ),int对应0

浙公网安备 33010602011771号