Convert nested Python dict to object?

后端 未结 30 1986
时光取名叫无心
时光取名叫无心 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:18

    This should get your started:

    class dict2obj(object):
        def __init__(self, d):
            self.__dict__['d'] = d
    
        def __getattr__(self, key):
            value = self.__dict__['d'][key]
            if type(value) == type({}):
                return dict2obj(value)
    
            return value
    
    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
    

    It doesn't work for lists, yet. You'll have to wrap the lists in a UserList and overload __getitem__ to wrap dicts.

提交回复
热议问题