Skip to content

Instantly share code, notes, and snippets.

@samukasmk
Created January 24, 2026 23:53
Show Gist options
  • Select an option

  • Save samukasmk/1ef8db7128571a74fa5b69f99ea67eef to your computer and use it in GitHub Desktop.

Select an option

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
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