Defining a Defaultdict
- A
defaultdictalmost behaves the same as adictionary -
If a user attempts to access a missing key:
- A
dictionarywill throw aKeyError - A
defaultdictwill 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'])
0Initializing 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