Convert nested Python dict to object? Convert nested Python dict to object? python python

Convert nested Python dict to object?


Update: In Python 2.6 and onwards, consider whether the namedtuple data structure suits your needs:

>>> from collections import namedtuple>>> MyStruct = namedtuple('MyStruct', 'a b d')>>> s = MyStruct(a=1, b={'c': 2}, d=['hi'])>>> sMyStruct(a=1, b={'c': 2}, d=['hi'])>>> s.a1>>> s.b{'c': 2}>>> s.cTraceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: 'MyStruct' object has no attribute 'c'>>> s.d['hi']

The alternative (original answer contents) is:

class Struct:    def __init__(self, **entries):        self.__dict__.update(entries)

Then, you can use:

>>> args = {'a': 1, 'b': 2}>>> s = Struct(**args)>>> s<__main__.Struct instance at 0x01D6A738>>>> s.a1>>> s.b2


Surprisingly no one has mentioned Bunch. This library is exclusively meant to provide attribute style access to dict objects and does exactly what the OP wants. A demonstration:

>>> from bunch import bunchify>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}>>> x = bunchify(d)>>> x.a1>>> x.b.c2>>> x.d[1].foo'bar'

A Python 3 library is available at https://github.com/Infinidat/munch - Credit goes to codyzu


class obj(object):    def __init__(self, d):        for a, b in d.items():            if isinstance(b, (list, tuple)):               setattr(self, a, [obj(x) if isinstance(x, dict) else x for x in b])            else:               setattr(self, a, obj(b) if isinstance(b, dict) else b)>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}>>> x = obj(d)>>> x.b.c2>>> x.d[1].foo'bar'