Skip to content

Instantly share code, notes, and snippets.

@lvm
Created August 28, 2020 05:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lvm/7fbba1dfc3b9bcce21f34bbb10288866 to your computer and use it in GitHub Desktop.
Save lvm/7fbba1dfc3b9bcce21f34bbb10288866 to your computer and use it in GitHub Desktop.
Flat nested dicts.
def flatten(dct: dict, , prefix="", glue: str = "__") -> dict:
flat = {}
prefix = f"{prefix}{glue}" if prefix else ""
def _flat(dct):
_dct = {}
for k, v in dct.items():
if not isinstance(v, list) and not isinstance(v, dict):
_dct[k] = v
elif isinstance(v, dict):
for kd, vd in v.items():
_dct[kd] = vd
return _dct
if not isinstance(dct, list) and not isinstance(dct, dict):
return dct
if isinstance(dct, list):
idx = 0
for child in dct:
_key = f"{prefix}{idx}"
flat[_key] = flatten(child, _key)
idx += 1
if isinstance(dct, dict):
for key, value in dct.items():
_key = f"{prefix}{key}"
flat[_key] = flatten(value, _key)
flat = _flat(flat)
return flat
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment