summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJohn Estabrook <jestabro@vyos.io>2020-07-01 12:34:18 -0500
committerJohn Estabrook <jestabro@vyos.io>2020-07-01 13:25:49 -0500
commit384d2f10aa7e84dbde8900cb526d05a35eac2b15 (patch)
treeebf64726d4a6d3da2281ad835ff9df3763eb4efa
parentf4892241d8248d0e22f971fdc3acd897c7035be9 (diff)
downloadvyos-1x-384d2f10aa7e84dbde8900cb526d05a35eac2b15.tar.gz
vyos-1x-384d2f10aa7e84dbde8900cb526d05a35eac2b15.zip
config: T2667: add utility function get_sub_dict
-rw-r--r--python/vyos/util.py30
1 files changed, 30 insertions, 0 deletions
diff --git a/python/vyos/util.py b/python/vyos/util.py
index 0ddc14963..268eaa69a 100644
--- a/python/vyos/util.py
+++ b/python/vyos/util.py
@@ -364,6 +364,36 @@ def mangle_dict_keys(data, regex, replacement):
return new_dict
+def _get_sub_dict(d, lpath):
+ k = lpath[0]
+ if k not in d.keys():
+ return {}
+ c = {k: d[k]}
+ lpath = lpath[1:]
+ if not lpath:
+ return c
+ elif not isinstance(c[k], dict):
+ return {}
+ return _get_sub_dict(c[k], lpath)
+
+def get_sub_dict(source, lpath):
+ """ Returns the sub-dict of a nested dict, defined by path of keys.
+
+ Args:
+ source (dict): Source dict to extract from
+ lpath (list[str]): sequence of keys
+
+ Returns: {key : source[..]..[key]} for key the last element of lpath, if exists
+ {} otherwise
+ """
+ if not isinstance(source, dict):
+ raise TypeError("source must be of type dict")
+ if not isinstance(lpath, list):
+ raise TypeError("path must be of type list")
+ if not lpath:
+ return source
+ return _get_sub_dict(source, lpath)
+
def process_running(pid_file):
""" Checks if a process with PID in pid_file is running """
from psutil import pid_exists