Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import dpath.util
def dpath_null(data: dict, path: str, default_return = None):
'''function to trap any KeyErrors for dpath and return an acceptable 'null' value when dpath can't find a path
Example 1
---------
# Will return None if /some/path/to/an/attribute can not be found
var = dpath_null(my_dictionary, '/some/path/to/an/attribute')
Example 2
---------
# Will return empty list if /some/path/to/a/list/attribute can not be found
var = dpath_null(my_dictionary, '/some/path/to/a/list/attribute', [])
Parameters
----------
- data (dict):
dictionary to search
- path (str):
path to search
- default_return:
value to return when dpath can't find a value for a path
Returns
-------
- None:
Returns None, or value provided as the default_return value
'''
try:
return dpath.util.get(data, path)
except KeyError as ex:
return default_return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment