📜  python safe get from dict - Python(1)

📅  最后修改于: 2023-12-03 15:04:08.393000             🧑  作者: Mango

Python Safe Get from Dict - Python

In Python, accessing a dictionary key that does not exist raises a KeyError exception. To prevent this and gracefully handle missing keys, one approach is to use the get() method of a dictionary, which allows you to specify a default value to return if the key does not exist.

Here is an example of using get():

my_dict = {'a': 1, 'b': 2}
value = my_dict.get('c', 0)
print(value)  # Output: 0

In the example above, my_dict.get('c', 0) returns the value associated with the key 'c', which does not exist in the dictionary, but instead of raising an exception, it returns the default value 0.

However, there are cases where the value associated with a key could itself be None, and we still need to handle that case. One solution is to chain multiple get() calls, like this:

my_dict = {'a': {'b': {'c': None}}}
value = my_dict.get('a', {}).get('b', {}).get('c', 'default')
print(value)  # Output: None

In the example above, we first call my_dict.get('a', {}) to get the value associated with the key 'a', or an empty dictionary {} if the key is missing. Then we call get() on that value with another dictionary {} as the default, and so on.

To avoid this repetitive code, we can define a helper function that recursively handles nested dictionaries and returns the default value if the entire chain of keys does not exist. Here is an implementation:

def safe_get(data, *keys, default=None):
    for key in keys:
        if isinstance(data, dict):
            data = data.get(key, {})
        else:
            return default
    return data if data is not None else default

The safe_get() function takes a dictionary data, a variable number of keys that form the chain of nested keys, and a default value to return if the entire chain of keys does not exist. It then loops through the keys and uses get() to retrieve the next level of nested data, or an empty dictionary {} if the key is missing. If at any point the data is not a dictionary, the function returns the default value. Finally, if the data is not None, it returns the value, otherwise it returns the default.

Here is an example of using safe_get():

my_dict = {'a': {'b': {'c': None}}}
value = safe_get(my_dict, 'a', 'b', 'c', default='default')
print(value)  # Output: None

In the example above, safe_get(my_dict, 'a', 'b', 'c', default='default') returns the value associated with the key ['a']['b']['c'], which is None. However, if any of the keys 'a', 'b', or 'c' did not exist, the function would return the default value 'default'.

In summary, when working with nested dictionaries in Python, it is important to handle missing keys gracefully to prevent errors. Using the get() method of a dictionary with a default value is one approach, and defining a helper function like safe_get() can make the code more concise and easier to read.