fork download
  1. # Conventional Hello World in Jython
  2. print "Hello World!"
  3.  
  4. def flatten_with_path(obj):
  5. """
  6. Flatten a nested structure (dicts, lists, or variables) into a list of tuples
  7. with each tuple containing the value and its path in the original structure.
  8. """
  9. flattened = []
  10.  
  11. # Helper function to recursively flatten with path
  12. def _flatten_helper(item, path):
  13. if isinstance(item, dict):
  14. for key, value in item.items():
  15. _flatten_helper(value, path + [key])
  16. elif isinstance(item, list):
  17. for index, value in enumerate(item):
  18. _flatten_helper(value, path + [index])
  19. else:
  20. flattened.append((item, path))
  21.  
  22. # Call the helper function to start the recursion
  23. _flatten_helper(obj, [])
  24.  
  25. return flattened
  26.  
  27. nested_data = [
  28. {
  29. "name": "John",
  30. "age": 30,
  31. "children": [
  32. {"name": "Alice", "age": 5},
  33. {"name": "Bob", "age": 8}
  34. ]
  35. },
  36. ["apple", "banana", ["orange", "grape"]],
  37. "hello"
  38. ]
  39. flatten_with_path(nested_data)
  40.  
Success #stdin #stdout 0.01s 7072KB
stdin
Standard input is empty
stdout
Hello World!