Last active
November 9, 2025 16:04
-
-
Save manatlan/24ec7c866311cbe66575b88076e336dc to your computer and use it in GitHub Desktop.
Convert dict to dict with attribut
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
| class Jdict(dict): | |
| def __new__(cls, obj): | |
| if isinstance(obj, dict): | |
| instance = super().__new__(cls) | |
| instance.update(obj) | |
| return instance | |
| elif isinstance(obj, list): | |
| return [cls(i) for i in obj] | |
| else: | |
| return obj | |
| def __getattr__(self, name: str): | |
| if name in self: | |
| return Jdict(self[name]) | |
| else: | |
| return f"?{name}?" | |
| if __name__=="__main__": | |
| x=Jdict(dict(a=12)) | |
| print(x) # -> {'a': 12} | |
| print(x.a) # -> 12 | |
| print(x.b) # -> '?b?' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment