summaryrefslogtreecommitdiff
path: root/python
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 /python
parenteb3c88023c7768ac9cbb5a84f78a71edcb798137 (diff)
downloadvyos-1x-f406d48b527589200611dcbb5a99044489b1e9c5.tar.gz
vyos-1x-f406d48b527589200611dcbb5a99044489b1e9c5.zip
vyos.utils: T7740: update dict_search to return optional default value (#4700)
Diffstat (limited to 'python')
-rw-r--r--python/vyos/utils/dict.py19
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