Created
May 17, 2019 02:33
-
-
Save ezirmusitua/d5db78a601ad947c37779290d45f971b to your computer and use it in GitHub Desktop.
[Flatten dict] flatten nested dict #python
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
# 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