Show the difference between direct key access and get() on a Python dictionary, including a default value.
There are two ways to read a value out of a dictionary, and the only difference between them shows up when the key is missing. Square brackets raise a KeyError when the key is not there. The get() method returns a fallback value instead, and it never raises an error.
data = {'name': 'Ada'}
print(data['name']) # Ada
print(data.get('name')) # Ada - the same result when the key exists
print(data.get('age')) # None - the default is None
print(data.get('age', 0)) # 0 - your own default
try:
print(data['age'])
except KeyError as error:
print('KeyError:', error)
When the key does exist, the two forms behave in exactly the same way. That is why the choice only matters on the failure path, and why you can change one into the other without thinking about it.
There is a second difference that is easier to miss. It appears when the key exists but the value stored in it is None. Both forms give you None in that case, so neither one tells you that the key is present. If you need to tell a missing key apart from a key that holds None, use the membership test with the in keyword.
data = {'name': 'Ada', 'nickname': None}
print('name in data ->', 'name' in data)
print('nickname in data ->', 'nickname' in data)
print('missing in data ->', 'missing' in data)
Choosing between the two forms is really a decision about what a missing key means. If a missing key means that the data is broken, such as a configuration value that must be present or a required field in a payload, then let the KeyError happen. The error message names the missing key and stops the program at the place where the problem is, which is exactly what you want in a request handler or in a data pipeline.
If a missing key is a normal possibility, use get(). That covers optional settings, a search that may find nothing, and any lookup where a sensible default exists. When the default is a real value rather than None, pass it in explicitly, so that the intent is visible at the place where the value is used.