Convert nested Python dict to object?

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

    You can leverage the json module of the standard library with a custom object hook:

    import json
    
    class obj(object):
        def __init__(self, dict_):
            self.__dict__.update(dict_)
    
    def dict2obj(d):
        return json.loads(json.dumps(d), object_hook=obj)
    

    Example usage:

    >>> d = {'a': 1, 'b': {'c': 2}, 'd': ['hi', {'foo': 'bar'}]}
    >>> o = dict2obj(d)
    >>> o.a
    1
    >>> o.b.c
    2
    >>> o.d[0]
    u'hi'
    >>> o.d[1].foo
    u'bar'
    

    And it is not strictly read-only as it is with namedtuple, i.e. you can change values – not structure:

    >>> o.b.c = 3
    >>> o.b.c
    3
    

提交回复
热议问题