Convert nested Python dict to object?

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

    Here's another implementation:

    class DictObj(object):
        def __init__(self, d):
            self.__dict__ = d
    
    def dict_to_obj(d):
        if isinstance(d, (list, tuple)): return map(dict_to_obj, d)
        elif not isinstance(d, dict): return d
        return DictObj(dict((k, dict_to_obj(v)) for (k,v) in d.iteritems()))
    

    [Edit] Missed bit about also handling dicts within lists, not just other dicts. Added fix.

提交回复
热议问题