Created
January 24, 2026 23:53
-
-
Save samukasmk/1ef8db7128571a74fa5b69f99ea67eef to your computer and use it in GitHub Desktop.
Convert dict (and lists) to objects with accessible attribute by each key recursively
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 __future__ import annotations | |
| from types import SimpleNamespace | |
| from collections.abc import Mapping | |
| from typing import Any | |
| def to_namespace(value: Any) -> Any: | |
| if isinstance(value, Mapping): | |
| return SimpleNamespace(**{k: to_namespace(v) for k, v in value.items()}) | |
| if isinstance(value, list): | |
| return [to_namespace(v) for v in value] | |
| if isinstance(value, tuple): | |
| return tuple(to_namespace(v) for v in value) | |
| return value | |
| data = {"a": 1, "b": {"c": 2, "d": [{"e": 3}]}} | |
| o = to_namespace(data) | |
| print(o.b.c) # 2 | |
| print(o.b.d[0].e) # 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment