summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorl0crian1 <143656816+l0crian1@users.noreply.github.com>2025-09-14 07:44:47 -0400
committerGitHub <noreply@github.com>2025-09-14 13:44:47 +0200
commitf406d48b527589200611dcbb5a99044489b1e9c5 (patch)
treed10f8f723f5eab50ac85462028d66ed3bdee0944
parenteb3c88023c7768ac9cbb5a84f78a71edcb798137 (diff)
downloadvyos-1x-f406d48b527589200611dcbb5a99044489b1e9c5.tar.gz
vyos-1x-f406d48b527589200611dcbb5a99044489b1e9c5.zip
vyos.utils: T7740: update dict_search to return optional default value (#4700)
-rw-r--r--python/vyos/utils/dict.py19
-rw-r--r--src/tests/test_dict_search.py8
2 files changed, 22 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
diff --git a/src/tests/test_dict_search.py b/src/tests/test_dict_search.py
index ed147ec01..cbc170ecf 100644
--- a/src/tests/test_dict_search.py
+++ b/src/tests/test_dict_search.py
@@ -44,6 +44,14 @@ class TestDictSearch(TestCase):
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'])