Created
August 20, 2012 08:55
-
-
Save mahmoud/3402465 to your computer and use it in GitHub Desktop.
An ok way to flatten nested dictionaries in Python (iteratively, not recursively). Even does basic circularity checks (untested at this point).
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 flatten_dict(root, prefix_keys=True): | |
dicts = [([], root)] | |
ret = {} | |
seen = set() | |
for path, d in dicts: | |
if id(d) in seen: | |
continue | |
seen.add(id(d)) | |
for k, v in d.items(): | |
new_path = path + [k] | |
prefix = '_'.join(new_path) if prefix_keys else k | |
if hasattr(v, 'items'): | |
dicts.append((new_path, v)) | |
else: | |
ret[prefix] = v | |
return ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment