Skip to content

Instantly share code, notes, and snippets.

@Leechael
Created December 27, 2013 09:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Leechael/8144525 to your computer and use it in GitHub Desktop.
Save Leechael/8144525 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# encoding: utf-8
class dict2obj(dict):
def __init__(self, d, default=None):
self.__d = d
self.__default = default
super(self.__class__, self).__init__(d)
def __getattr__(self, k):
if k in self.__d:
v = self.__d[k]
if isinstance(v, dict):
v = self.__class__(v)
setattr(self, k, v)
return v
return self.__default
a = {"b": {"c": 1}, "d": 2}
b = dict2obj(a)
print b.b.c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment