Created
October 23, 2012 08:53
-
-
Save nobonobo/3937729 to your computer and use it in GitHub Desktop.
Flattener from Nested Dict to 1d-dict
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 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