Created
November 18, 2014 15:12
-
-
Save mrgriscom/37986cb229023aad8e05 to your computer and use it in GitHub Desktop.
flatten a nested dict
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 dict_flatten(d, delim='.', prefix=[]): | |
def pairs(d, prefix): | |
def flatten(k, v): | |
if isinstance(v, dict): | |
return pairs(v, k) | |
else: | |
return [(k, v)] | |
for k, v in d.iteritems(): | |
for e in flatten(prefix + [k], v): | |
yield e | |
return dict((delim.join(k), v) for k, v in pairs(d, prefix)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment