Convert nested Python dict to object?

后端 未结 30 2445
时光取名叫无心
时光取名叫无心 2020-11-22 09:28

I\'m searching for an elegant way to get data using attribute access on a dict with some nested dicts and lists (i.e. javascript-style object syntax).

For example:

30条回答
  •  耶瑟儿~
    2020-11-22 10:21

    >>> 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)
    >>> x.a
    1
    >>> x.b.c
    2
    >>> x.d[1].foo
    'bar'
    

提交回复
热议问题