Define a variable when using dict variables

v = dict()
v[key] = value
Copy the code

Adding a key value to a dictionary type Raises an exception if access does not have a key

>>> v['unknown_k']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'unknown_k'
>>>
Copy the code

You can use the following GET method with default values

>>> v.get('unknown_k', 'something not found')
'something not found'
Copy the code

The other method uses Defaultdict to create variables using factory functions as arguments, as shown below

>>> from collections import defaultdict
>>> v = defaultdict(str)
>>> v
defaultdict(<class 'str'>, {})
>>> v['unknown_key']
''
Copy the code

The factory function can be list, set, STR, etc. When accessing a key that does not exist in the dictionary, the factory function returns the default values of list [], set (), and STR ”.