Skip to content

Instantly share code, notes, and snippets.

@saracen24
Created May 28, 2024 13:43
Show Gist options
  • Select an option

  • Save saracen24/43965b7ae07ac584a3a7047d48c29522 to your computer and use it in GitHub Desktop.

Select an option

Save saracen24/43965b7ae07ac584a3a7047d48c29522 to your computer and use it in GitHub Desktop.
Convert a dict of any depth to a class.
from typing import Any, Dict, FrozenSet, List, Set, Tuple, Union
class DictToClass:
"""Convert a dict of any depth to a class."""
def __init__(self, data: Dict) -> None:
for name, value in data.items():
setattr(self, name, self.__expand(value))
def __expand(self, value: Any) -> Union["DictToClass", Any]:
if isinstance(value, (Tuple, List, Set, FrozenSet)):
return type(value)([self.__expand(v) for v in value])
else:
return DictToClass(value) if isinstance(value, Dict) else value
@saracen24
Copy link
Author

saracen24 commented May 28, 2024

Usage

from .dict_to_class import DictToClass

data = {
    "a": "str",
    "b": 42,
    "c": 0.5,
    "d": {"e": 2.5},
    "f": [0, 1, 2, 3, 4, 5],
}
struct = DictToClass(data)

print(struct.a)
print(struct.b)
print(struct.c)
print(struct.d.e)
print(struct.f)

Output

str
42
0.5
2.5
[0, 1, 2, 3, 4, 5]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment