Python dictionaries: Avoiding KeyError with dict.get

Python dictionaries: Avoiding KeyError with dict.get

Retrieve a value from a Python dict with the key:

d = {'a':10, 'b':20}
d['a']  # returns 10

Request a key that doesn’t exist:

d['x']  # KeyError

Avoid that with dict.get, what I call “forgiving []”

d.get('a')     # 10
d.get('x')     # None
d.get('x', 0)  # returns 0