Guest User

Untitled

a guest
Jul 22nd, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. """
  2. Extract from a given dictionary all available paths as a list of nodes.
  3. """
  4. import copy
  5.  
  6.  
  7. def get_paths_from_dict(in_dict, io_final_list=None, io_temp_list=None):
  8. """
  9. Compute available paths as a list of nodes from dictionary, recursively.
  10.  
  11. :param in_dict: Dictionary
  12. :param io_final_list: Starting list (default is empty)
  13. :param io_temp_list: Intermediate input for having a temporary list (empty also)
  14. :return: List of paths as a list of nodes
  15. """
  16. if io_temp_list is None:
  17. io_temp_list = []
  18. if io_final_list is None:
  19. io_final_list = []
  20. for key, val in in_dict.items():
  21. if isinstance(val, dict):
  22. io_temp_list.append(key)
  23. get_paths_from_dict(val, io_final_list, io_temp_list)
  24. io_temp_list.pop(-1)
  25. else:
  26. if io_temp_list:
  27. v = copy.deepcopy(io_temp_list)
  28. v.append(key)
  29. v.append("#") # any tag here for end of tree
  30. io_final_list.append(v)
  31. else:
  32. io_final_list.append([key, "#"]) # any tag here for end of tree
  33.  
  34. val_list = []
  35. for row in io_final_list:
  36. if row[-1] == "#":
  37. val_list.append(row[0:-1])
  38.  
  39. return val_list
  40.  
  41.  
  42. if __name__ == '__main__':
  43. """
  44. Testing
  45. """
  46.  
  47. dict_test = {
  48. "a": "value a",
  49. "b": {
  50. "b.1": "value b.1",
  51. "b.2": {
  52. "b.2.1": "value b.2.1",
  53. "b.2.2": {
  54. "b.2.2.1": "value b.2.2",
  55. },
  56. "b.2.3": "value b.2.3",
  57. },
  58. "b.3": "value b.3",
  59. "b.4": "value b.4",
  60. "b.5": {
  61. "b.5.1": "value b.5.1",
  62. "b.5.2": {
  63. "b.5.2.1": "value b.5.2.1",
  64. }
  65. },
  66. },
  67. "c": {
  68. "c.1": "value c",
  69. },
  70. "d": "value d",
  71. }
  72.  
  73. expected_output = [
  74. ["a"],
  75. ["b", "b.1"],
  76. ["b", "b.2", "b.2.1"],
  77. ["b", "b.2", "b.2.2", "b.2.2.1"],
  78. ["b", "b.2", "b.2.3"],
  79. ["b", "b.3"],
  80. ["b", "b.4"],
  81. ["b", "b.5", "b.5.1"],
  82. ["b", "b.5", "b.5.2", "b.5.2.1"],
  83. ["c", "c.1"],
  84. ["d"],
  85. ]
  86.  
  87. print("expected", expected_output)
  88. print("found ..", get_paths_from_dict(dict_test))
Add Comment
Please, Sign In to add comment