For those using the dict.get
technique for nested dictionaries, instead of explicitly checking for every level of the dictionary, or extending the dict
class, you can set the default return value to an empty dictionary except for the out-most level. Here's an example:
my_dict = {'level_1': {
'level_2': {
'level_3': 'more_data'
}
}
}
result = my_dict.get('level_1', {}).get('level_2', {}).get('level_3')
# result -> 'more_data'
none_result = my_dict.get('level_1', {}).get('what_level', {}).get('level_3')
# none_result -> None
WARNING: Please note that this technique only works if the expected key's value is a dictionary. If the key what_level
did exist in the dictionary but its value was a string or integer etc., then it would've raised an AttributeError
.
.get(key)
instead of[key]
– Gabe