My question is similar to Finding a key recursively in a dictionary except that once I find the key, I would like to list all parent keys that lead me to the target key.
Logically, I feel like I know what I need to do: store the "path" by appending keys to a list as I descend into the dictionary. If I get to the "bottom" of the dictionary and don't find the key I'm looking for, then I need to reset the path. But, I can't think how do implement this in Python. My current solution just prints out the target key in a list:
def list_parents(obj, key):
path = []
if key in obj:
path.append(key)
return path
for k, v in obj.items():
if isinstance(v, dict):
path.extend(list_parents(v, key))
return path