diff options
Diffstat (limited to 'python')
| -rw-r--r-- | python/vyos/utils/dict.py | 19 |
1 files changed, 14 insertions, 5 deletions
diff --git a/python/vyos/utils/dict.py b/python/vyos/utils/dict.py index a43430eed..5d41900b6 100644 --- a/python/vyos/utils/dict.py +++ b/python/vyos/utils/dict.py @@ -145,24 +145,33 @@ def get_sub_dict(source, lpath, get_first_key=False): return ret -def dict_search(path, dict_object): +def dict_search(path, dict_object, default=None): """ Traverse Python dictionary (dict_object) delimited by dot (.). - Return value of key if found, None otherwise. + + Args: + path (str): Dot-delimited key path, e.g. "foo.bar.baz". + dict_object (dict): The dictionary to search. + default (Any, optional): Value to return if the path is not found + or if dict_object is not a dict. Defaults to None. + + Returns: + Any: The value found at the given path, or None if not found. Optionally, + a default value can be provided to be returned. This is faster implementation then jmespath.search('foo.bar', dict_object)""" if not isinstance(dict_object, dict) or not path: - return None + return default parts = path.split('.') inside = parts[:-1] if not inside: if path not in dict_object: - return None + return default return dict_object[path] c = dict_object for p in parts[:-1]: c = c.get(p, {}) - return c.get(parts[-1], None) + return c.get(parts[-1], default) def dict_search_args(dict_object, *path): # Traverse dictionary using variable arguments |
