2. Accessing a dictionary value with a default value

Use dict.get when the missing-key case should fall back to a default value.

It is a concise way to say that missing data is expected and should not be exceptional. That makes the fallback value part of the expression instead of scattering default-handling branches around the code.

2.1. Don’t do this

1d = {
2    'username': 'jdoe'
3}
4
5is_authorized = False
6if 'auth_token' in d:
7    is_authorized = True
1d = {
2    'username': 'jdoe'
3}
4
5is_authorized = True if 'auth_token' in d else False

2.2. Do this

1d = {
2    'username': 'jdoe',
3    'theme': 'dark',
4}
5
6theme = d.get('theme', 'light')