Convert nested Python dict to object?

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

    Update: In Python 2.6 and onwards, consider whether the namedtuple data structure suits your needs:

    >>> from collections import namedtuple
    >>> MyStruct = namedtuple('MyStruct', 'a b d')
    >>> s = MyStruct(a=1, b={'c': 2}, d=['hi'])
    >>> s
    MyStruct(a=1, b={'c': 2}, d=['hi'])
    >>> s.a
    1
    >>> s.b
    {'c': 2}
    >>> s.c
    Traceback (most recent call last):
      File "", line 1, in 
    AttributeError: 'MyStruct' object has no attribute 'c'
    >>> s.d
    ['hi']
    

    The alternative (original answer contents) is:

    class Struct:
        def __init__(self, **entries):
            self.__dict__.update(entries)
    

    Then, you can use:

    >>> args = {'a': 1, 'b': 2}
    >>> s = Struct(**args)
    >>> s
    <__main__.Struct instance at 0x01D6A738>
    >>> s.a
    1
    >>> s.b
    2
    

提交回复
热议问题