Defining a Defaultdict
- A
defaultdict
almost behaves the same as adictionary
-
If a user attempts to access a missing key:
- A
dictionary
will throw aKeyError
- A
defaultdict
will create an item using a default value
- A
- This is one of the only differences between the two
Differentiating between dict
and defaultdict
>>> d = {}
>>> d['hello']
KeyError: 'hello'
>>> from collections import defaultdict
>>> dd = defaultdict(int)
>>> dd['hello']
0
>>> print(dd)
defaultdict(<class 'int'>, {'hello': 0})
>>> print(dd['hello'])
0
Initializing a Defaultdict
>>> from collections import defaultdict
>>> dd = defaultdict(int)
>>> print(dd)
defaultdict(<class 'int'>, {})
Adding to a Defaultdict
>>> from collections import defaultdict
>>> dd = defaultdict(list)
>>> dd['hello']
[]
>>> print(dd)
defaultdict(<class 'list'>, {'hello': []})
References
Previous
Next