From a55bbcc8ec25a3616b7f6396ee14168a707f18eb Mon Sep 17 00:00:00 2001 From: Viacheslav Hletenko Date: Sun, 12 Feb 2023 18:30:23 +0000 Subject: T4999: Backport vyos util dict_search_recursive Backport "dict_search_recursive" from vyos.util 1.4 to 1.3 data = { 'interfaces': {'dummy': {'dum0': {'address': ['192.0.2.17/29']}}, 'ethernet': {'eth0': {'address': ['2001:db8::1/64', '192.0.2.1/29'], 'description': 'Test123', 'duplex': 'auto', 'hw_id': '00:00:00:00:00:01', 'speed': 'auto'}, 'eth1': {'address': ['192.0.2.9/29'], 'description': 'Test456', 'duplex': 'auto', 'hw_id': '00:00:00:00:00:02', 'speed': 'auto'}}} } dict_search_recursive(data, 'hw_id') will yield both '00:00:00:00:00:01' and '00:00:00:00:00:02' as generator object. --- python/vyos/util.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) (limited to 'python') diff --git a/python/vyos/util.py b/python/vyos/util.py index 5c6409341..32a5ae116 100644 --- a/python/vyos/util.py +++ b/python/vyos/util.py @@ -1,4 +1,4 @@ -# Copyright 2020-2022 VyOS maintainers and contributors +# Copyright 2020-2023 VyOS maintainers and contributors # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public @@ -720,6 +720,26 @@ def dict_search(path, dict_object): c = c.get(p, {}) return c.get(parts[-1], None) +def dict_search_recursive(dict_object, key, path=[]): + """ Traverse a dictionary recurisvely and return the value of the key + we are looking for. + Thankfully copied from https://stackoverflow.com/a/19871956 + Modified to yield optional path to found keys + """ + if isinstance(dict_object, list): + for i in dict_object: + new_path = path + [i] + for x in dict_search_recursive(i, key, new_path): + yield x + elif isinstance(dict_object, dict): + if key in dict_object: + new_path = path + [key] + yield dict_object[key], new_path + for k, j in dict_object.items(): + new_path = path + [k] + for x in dict_search_recursive(j, key, new_path): + yield x + def convert_data(data): """Convert multiple types of data to types usable in CLI -- cgit v1.2.3