Source

Dan Bader, Python Tricks: The Book

§7.1 Dictionary Default Values

1
2
3
4
5
mydict = {
    'a': 1,
    'b': 2,
    'c': 3,
}

One way to avoid a KeyError:

1
2
3
4
5
6
try:
    x = mydict['d']
except KeyError:
    x = 0
    
assert x == 0

Another: use dict.get(), which returns None:

1
2
y = mydict.get('d')
assert y is None

With the optional second argument representing a default value, returns that:

1
2
z = mydict.get('e', 0)
assert z == 0