Created
February 3, 2017 21:34
-
-
Save SegFaultAX/b926fe97c2ac1db1fb313f3a9372ee56 to your computer and use it in GitHub Desktop.
Traverse a Python dict and find all key paths
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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})] |
So useful ! Thanks for sharing this
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!