Last active
June 6, 2020 10:13
-
-
Save lucascheung/c0b1d2aa9436889b9f544f3fccd21625 to your computer and use it in GitHub Desktop.
Flatten any nested objects on 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
def flatten(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, MutableMapping): | |
items.extend(flatten(v, new_key, sep=sep).items()) | |
else: | |
items.append((new_key, v)) | |
return dict(items) | |
# For single layer list: | |
flat_list = [item for sublist in l for item in sublist] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment