Skip to content

Instantly share code, notes, and snippets.

@Lukse
Last active August 29, 2015 14:09
Show Gist options
  • Save Lukse/68e591b1876cbb94382c to your computer and use it in GitHub Desktop.
Save Lukse/68e591b1876cbb94382c to your computer and use it in GitHub Desktop.
dict2obj
def dict2obj(d):
if isinstance(d, list):
d = [dict2obj(x) for x in d]
if not isinstance(d, dict):
return d
class C(object):
pass
o = C()
for k in d:
o.__dict__[k] = dict2obj(d[k])
return o
d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
x = dict2obj(d)
print x.a
print x.b.c
print x.d[1].foo
print x.z
print x
# ============================
from collections import namedtuple
MyStruct = namedtuple('MyStruct', 'a b d')
s = MyStruct(a=1, b={'c': 2}, d=['hi'])
print s
print s.a
print s.b
print s.d
# ============================
https://github.com/dsc/bunch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment