Created
November 11, 2021 15:30
-
-
Save altescy/6467bc3caf68f608f43f5fa38edd46a7 to your computer and use it in GitHub Desktop.
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
from typing import Any, Dict | |
def flatten(data: Any, parent_key: str = "") -> Any: | |
if isinstance(data, list): | |
data = {str(i): x for i, x in enumerate(data)} | |
if not isinstance(data, dict): | |
return data | |
ret: Dict[str, Any] = {} | |
for key, value in data.items(): | |
value = flatten(value, key) | |
if isinstance(value, dict): | |
ret.update(value) | |
else: | |
ret[key] = value | |
if not parent_key: | |
return ret | |
return {f"{parent_key}.{k}": v for k, v in ret.items()} | |
def unflatten(data: Any) -> Any: | |
if not isinstance(data, dict): | |
return data | |
if all(key.isdigit() for key in data): | |
return [unflatten(value) for _, value in sorted(data.items())] | |
ret: Dict[str, Any] = {} | |
for key, value in sorted(data.items()): | |
value = unflatten(value) | |
if "." in key: | |
topkey, subkey = key.split(".", 1) | |
ret[topkey] = ret.get(topkey, {}) | |
ret[topkey][subkey] = value | |
else: | |
ret[key] = value | |
for key, value in ret.items(): | |
if isinstance(value, dict): | |
ret[key] = unflatten(value) | |
return ret | |
if __name__ == "__main__": | |
data = {"a": {"b": 1, "c": 2}, "d": {"e": {"f": [3, 4, 5]}}} | |
x = flatten(data) | |
y = unflatten(x) | |
print(x) | |
print(y) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment