default dictionary value 1

default dictionary value

>>> from collections import defaultdict
>>> d = {'foo': 123, 'bar': 456}
>>> d['baz']
Traceback (most recent call last):
  File "", line 1, in 
KeyError: 'baz'
>>> d = defaultdict(lambda: -1, d)
>>> d['baz']

Here is what the above code is Doing:
1. We import the defaultdict class from the collections module.
2. We create a dictionary d with two key-value pairs.
3. We try to access the value for the key ‘baz’. This raises a KeyError.
4. We create a defaultdict d with a default value of -1.
5. We access the value for the key ‘baz’. This returns -1.

Similar Posts