将嵌套的Python字典转换为对象?

发布于 2021-02-02 23:16:45

我正在寻找一种优雅的方式来获取数据,该数据使用具有一些嵌套dict和列表(例如javascript样式对象语法)的dict进行属性访问。

例如:

>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}

应该以这种方式访问​​:

>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
bar

我认为,没有递归是不可能的,但是获得字典对象样式的一种好方法是什么?

关注者
0
被浏览
67
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    更新:在Python 2.6及更高版本中,请考虑namedtuple数据结构是否满足你的需求:

    >>> 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 "<stdin>", line 1, in <module>
    AttributeError: 'MyStruct' object has no attribute 'c'
    >>> s.d
    ['hi']
    

    备选方案(原始答案内容)为:

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

    然后,你可以使用:

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看