Skip to content

Instantly share code, notes, and snippets.

@GaryRogers
Created January 28, 2020 16:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GaryRogers/b293ba52ac6971efe49ff00dbab06ed5 to your computer and use it in GitHub Desktop.
Save GaryRogers/b293ba52ac6971efe49ff00dbab06ed5 to your computer and use it in GitHub Desktop.
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