Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Extract from a given dictionary all available paths as a list of nodes.
- """
- import copy
- def get_paths_from_dict(in_dict, io_final_list=None, io_temp_list=None):
- """
- Compute available paths as a list of nodes from dictionary, recursively.
- :param in_dict: Dictionary
- :param io_final_list: Starting list (default is empty)
- :param io_temp_list: Intermediate input for having a temporary list (empty also)
- :return: List of paths as a list of nodes
- """
- if io_temp_list is None:
- io_temp_list = []
- if io_final_list is None:
- io_final_list = []
- for key, val in in_dict.items():
- if isinstance(val, dict):
- io_temp_list.append(key)
- get_paths_from_dict(val, io_final_list, io_temp_list)
- io_temp_list.pop(-1)
- else:
- if io_temp_list:
- v = copy.deepcopy(io_temp_list)
- v.append(key)
- v.append("#") # any tag here for end of tree
- io_final_list.append(v)
- else:
- io_final_list.append([key, "#"]) # any tag here for end of tree
- val_list = []
- for row in io_final_list:
- if row[-1] == "#":
- val_list.append(row[0:-1])
- return val_list
- if __name__ == '__main__':
- """
- Testing
- """
- dict_test = {
- "a": "value a",
- "b": {
- "b.1": "value b.1",
- "b.2": {
- "b.2.1": "value b.2.1",
- "b.2.2": {
- "b.2.2.1": "value b.2.2",
- },
- "b.2.3": "value b.2.3",
- },
- "b.3": "value b.3",
- "b.4": "value b.4",
- "b.5": {
- "b.5.1": "value b.5.1",
- "b.5.2": {
- "b.5.2.1": "value b.5.2.1",
- }
- },
- },
- "c": {
- "c.1": "value c",
- },
- "d": "value d",
- }
- expected_output = [
- ["a"],
- ["b", "b.1"],
- ["b", "b.2", "b.2.1"],
- ["b", "b.2", "b.2.2", "b.2.2.1"],
- ["b", "b.2", "b.2.3"],
- ["b", "b.3"],
- ["b", "b.4"],
- ["b", "b.5", "b.5.1"],
- ["b", "b.5", "b.5.2", "b.5.2.1"],
- ["c", "c.1"],
- ["d"],
- ]
- print("expected", expected_output)
- print("found ..", get_paths_from_dict(dict_test))
Add Comment
Please, Sign In to add comment