Skip to content

Instantly share code, notes, and snippets.

@SegFaultAX
Created February 3, 2017 21:34
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SegFaultAX/b926fe97c2ac1db1fb313f3a9372ee56 to your computer and use it in GitHub Desktop.
Save SegFaultAX/b926fe97c2ac1db1fb313f3a9372ee56 to your computer and use it in GitHub Desktop.
Traverse a Python dict and find all key paths
def iter_paths(d):
def iter1(d, path):
paths = []
for k, v in d.items():
if isinstance(v, dict):
paths += iter1(v, path + [k])
paths.append((path + [k], v))
return paths
return iter1(d, [])
d = {"foo": {"bar": {"baz": 123}, "spam": 456}, "eggs": 789}
import pprint
pprint.pprint(iter_paths(d))
## OUTPUT ##
# [(['eggs'], 789),
# (['foo', 'bar', 'baz'], 123),
# (['foo', 'bar'], {'baz': 123}),
# (['foo', 'spam'], 456),
# (['foo'], {'bar': {'baz': 123}, 'spam': 456})]
@PyotrAndreev
Copy link

Thank you!

@homata123
Copy link

So useful ! Thanks for sharing this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment