Skip to content

Instantly share code, notes, and snippets.

@lucascheung
Last active June 6, 2020 10:13
Show Gist options
  • Save lucascheung/c0b1d2aa9436889b9f544f3fccd21625 to your computer and use it in GitHub Desktop.
Save lucascheung/c0b1d2aa9436889b9f544f3fccd21625 to your computer and use it in GitHub Desktop.
Flatten any nested objects on Python
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