Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions python/vyos/utils/dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions src/tests/test_dict_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ def test_non_existing_keys(self):
self.assertEqual(dict_search('non_existing', data), None)
self.assertEqual(dict_search('non.existing.fancy.key', data), None)

def test_non_existing_keys_with_default_positional(self):
# TestDictSearch: Return a default value when querying for non-existent key (positional arg)
self.assertEqual(dict_search('non.existing.fancy.key', data, 'test'), 'test')

def test_non_existing_keys_with_default_named(self):
# TestDictSearch: Return a default value when querying for non-existent key (named arg)
self.assertEqual(dict_search('non.existing.fancy.key', data, default='test'), 'test')

def test_string(self):
# TestDictSearch: Return value when querying string
self.assertEqual(dict_search('string', data), data['string'])
Expand Down
Loading