Convert nested Python dict to object?

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

    The simplest way would be using collections.namedtuple.

    I find the following 4-liner the most beautiful, which supports nested dictionaries:

    def dict_to_namedtuple(typename, data):
        return namedtuple(typename, data.keys())(
            *(dict_to_namedtuple(typename + '_' + k, v) if isinstance(v, dict) else v for k, v in data.items())
        )
    

    The output will look good as well:

    >>> nt = dict_to_namedtuple('config', {
    ...     'path': '/app',
    ...     'debug': {'level': 'error', 'stream': 'stdout'}
    ... })
    
    >>> print(nt)
    config(path='/app', debug=config_debug(level='error', stream='stdout'))
    
    >>> print(nt.debug.level)
    'error'
    

提交回复
热议问题