Convert nested Python dict to object?

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

    If your dict is coming from json.loads(), you can turn it into an object instead (rather than a dict) in one line:

    import json
    from collections import namedtuple
    
    json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
    

    See also How to convert JSON data into a Python object.

提交回复
热议问题