Skip to content

Instantly share code, notes, and snippets.

@JamesGardiner
Created July 29, 2021 08:14
Show Gist options
  • Save JamesGardiner/029617e5c70d630a1a1f83d102de3196 to your computer and use it in GitHub Desktop.
Save JamesGardiner/029617e5c70d630a1a1f83d102de3196 to your computer and use it in GitHub Desktop.
Flatten dictionary
def flatten(data):
"""Flatten a nested dict.
Args:
data (dict): The dictionary to flatten
Returns:
dict: Flattened dictionary
"""
out = {}
for key, val in data.items():
if isinstance(val, dict):
val = [val]
if isinstance(val, list):
for subdict in val:
out.update(flatten(subdict))
else:
out[key] = val
return out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment