Last active
August 29, 2015 14:04
-
-
Save jrha/8b2a6a98861588737c61 to your computer and use it in GitHub Desktop.
Flatten a dictionary tree into a list of paths
This file contains 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 gen(d, pfx=()): | |
return ( | |
x for k, v in d.iteritems() | |
for x in ( | |
gen(v, pfx+(k,)) if isinstance(v, dict) else ((pfx+(k,), v),) | |
) | |
) | |
def flattendict(tree): | |
paths = [] | |
for k, v in dict(gen(tree)).iteritems(): | |
if not isinstance(v, list): | |
paths.append(('/'.join(k), v)) | |
paths.sort() | |
return paths | |
def test(): | |
test = { | |
'mayo': 'chicken', | |
'tomato': { | |
'bacon' : 'cheese', | |
'garlic' : 'basil', | |
}, | |
} | |
for r in flattendict(test): | |
print '/%s = %s' % r |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment