Skip to content

Instantly share code, notes, and snippets.

@Dminor7
Created November 9, 2021 08:22
Show Gist options
  • Save Dminor7/ac0a186e85304a7eaa27520a8b0bb4b8 to your computer and use it in GitHub Desktop.
Save Dminor7/ac0a186e85304a7eaa27520a8b0bb4b8 to your computer and use it in GitHub Desktop.
Flatten Nested Dictionary within list or having list items. #flatten #python
"""
Using a generator we can `yield` key and value pairs when the value is not an instance of `list` or `dict`
else we recursively call the function to flatten the object. To preserve empty `list` and `dict`
we add additional check on obj when checking the obj type.
"""
def flatten(obj, prefix=[], sep="_"):
if isinstance(obj, list) and obj:
for i, o in enumerate(obj):
yield from flatten(o, prefix=prefix + [str(i)], sep=sep)
elif isinstance(obj, dict) and obj:
for k, v in obj.items():
yield from flatten(v, prefix=prefix + [k], sep=sep)
else:
yield (sep.join(prefix), obj)
obj = [
{
"a": {"b": 1, "c": 2},
"d": [3, 4, 5],
"e": {"f": True, "g": False},
"h": [{"i": 6, "j": 7}, {"i": 8, "j": 9}, {"i": 10, "j": 11}],
"k" : {"a":{}}
}
]
print(dict(flatten(obj, sep="_")))
"""
Output:
{'0_a_b': 1,
'0_a_c': 2,
'0_d_0': 3,
'0_d_1': 4,
'0_d_2': 5,
'0_e_f': True,
'0_e_g': False,
'0_h_0_i': 6,
'0_h_0_j': 7,
'0_h_1_i': 8,
'0_h_1_j': 9,
'0_h_2_i': 10,
'0_h_2_j': 11,
'0_k_a': {}}
Note: This code snippet assumes that the keys will be of type `str`.
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment