Open this example in the interactive library
Source code
def paths(node, target, trail=()):
if isinstance(node, list):
for i, child in enumerate(node):
yield from paths(child, target, trail+(i,))
elif isinstance(node, dict):
for key, child in node.items():
yield from paths(child, target, trail+(key,))
elif node == target:
yield trail
print(list(paths({'items': ['new', {'state': 'new'}]}, 'new')))
Sample output
[('items', 0), ('items', 1, 'state')]