Convert nested Python dict to object?

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

    Surprisingly no one has mentioned Bunch. This library is exclusively meant to provide attribute style access to dict objects and does exactly what the OP wants. A demonstration:

    >>> from bunch import bunchify
    >>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
    >>> x = bunchify(d)
    >>> x.a
    1
    >>> x.b.c
    2
    >>> x.d[1].foo
    'bar'
    

    A Python 3 library is available at https://github.com/Infinidat/munch - Credit goes to codyzu

提交回复
热议问题