Skip to content

Instantly share code, notes, and snippets.

@nobonobo
Created October 23, 2012 08:53
Show Gist options
  • Save nobonobo/3937729 to your computer and use it in GitHub Desktop.
Save nobonobo/3937729 to your computer and use it in GitHub Desktop.
Flattener from Nested Dict to 1d-dict
def flat(d):
res = []
for k,v in d.items():
if isinstance(v, dict):
res.extend([('.'.join([k,ck]), cv) for ck, cv in flat(v).items()])
else:
res.append((k,v))
return dict(res)
> print flat(dict(a=123, b=dict(c=1,d=dict(e='h',f='g',g='j'))))
{'a': 123, 'b.c': 1, 'b.d.g': 'j', 'b.d.f': 'g', 'b.d.e': 'h'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment