Skip to content

Instantly share code, notes, and snippets.

@ezirmusitua
Created May 17, 2019 02:33
Show Gist options
  • Save ezirmusitua/d5db78a601ad947c37779290d45f971b to your computer and use it in GitHub Desktop.
Save ezirmusitua/d5db78a601ad947c37779290d45f971b to your computer and use it in GitHub Desktop.
[Flatten dict] flatten nested dict #python
# reference: https://stackoverflow.com/questions/6027558/flatten-nested-dictionaries-compressing-keys
import collections
def flatten_nested_dict(d, parent_key='', sep='_'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, collections.MutableMapping):
items.extend(flatten(v, new_key, sep=sep).items())
else:
items.append((new_key, v))
return dict(items)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment