Convert nested Python dict to object?

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

    x = type('new_dict', (object,), d)
    

    then add recursion to this and you're done.

    edit this is how I'd implement it:

    >>> d
    {'a': 1, 'b': {'c': 2}, 'd': ['hi', {'foo': 'bar'}]}
    >>> def obj_dic(d):
        top = type('new', (object,), d)
        seqs = tuple, list, set, frozenset
        for i, j in d.items():
            if isinstance(j, dict):
                setattr(top, i, obj_dic(j))
            elif isinstance(j, seqs):
                setattr(top, i, 
                    type(j)(obj_dic(sj) if isinstance(sj, dict) else sj for sj in j))
            else:
                setattr(top, i, j)
        return top
    
    >>> x = obj_dic(d)
    >>> x.a
    1
    >>> x.b.c
    2
    >>> x.d[1].foo
    'bar'
    

提交回复
热议问题