Created
August 28, 2020 05:03
-
-
Save lvm/7fbba1dfc3b9bcce21f34bbb10288866 to your computer and use it in GitHub Desktop.
Flat nested dicts.
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(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