Created
July 29, 2021 08:14
-
-
Save JamesGardiner/029617e5c70d630a1a1f83d102de3196 to your computer and use it in GitHub Desktop.
Flatten dictionary
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(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