Skip to content

Instantly share code, notes, and snippets.

@mahmoud
Created August 20, 2012 08:55
Show Gist options
  • Save mahmoud/3402465 to your computer and use it in GitHub Desktop.
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).
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