Convert nested Python dict to object?

后端 未结 30 1987
时光取名叫无心
时光取名叫无心 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条回答
  •  -上瘾入骨i
    2020-11-22 10:08

    I stumbled upon the case I needed to recursively convert a list of dicts to list of objects, so based on Roberto's snippet here what did the work for me:

    def dict2obj(d):
        if isinstance(d, dict):
            n = {}
            for item in d:
                if isinstance(d[item], dict):
                    n[item] = dict2obj(d[item])
                elif isinstance(d[item], (list, tuple)):
                    n[item] = [dict2obj(elem) for elem in d[item]]
                else:
                    n[item] = d[item]
            return type('obj_from_dict', (object,), n)
        elif isinstance(d, (list, tuple,)):
            l = []
            for item in d:
                l.append(dict2obj(item))
            return l
        else:
            return d
    

    Note that any tuple will be converted to its list equivalent, for obvious reasons.

    Hope this helps someone as much as all your answers did for me, guys.

提交回复
热议问题