Advertisement
Guest User

Untitled

a guest
Sep 23rd, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.55 KB | None | 0 0
  1. import functools
  2.  
  3. @functools.singledispatch
  4. def find_path_to(obj, target):
  5. if obj == target:
  6. yield ()
  7.  
  8. @find_path_to.register(list)
  9. def _(seq, target):
  10. for idx, item in enumerate(seq):
  11. for path in find_path_to(item, target):
  12. yield (idx,) + path
  13.  
  14. @find_path_to.register(dict)
  15. def _(d, target):
  16. for key, value in d.items():
  17. for path in find_path_to(value, target):
  18. yield (key,) + path
  19.  
  20. data = [1, 2, 3, {4: 5, 6: 2, 7: [[[[[[2]]]]]]}]
  21. for path in find_path_to(data, 2):
  22. print(path)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement