Skip to content

Instantly share code, notes, and snippets.

@jrha
Last active August 29, 2015 14:04
Show Gist options
  • Save jrha/8b2a6a98861588737c61 to your computer and use it in GitHub Desktop.
Save jrha/8b2a6a98861588737c61 to your computer and use it in GitHub Desktop.
Flatten a dictionary tree into a list of paths
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