问题描述
我正在寻找一种优雅的方式来使用字典上的属性访问来获取数据,其中包含一些嵌套的字典和列表(即 javascript 样式的对象语法).
例如:
>>>d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}应该可以通过这种方式访问:
>>>x = dict2obj(d)>>>x.a1>>>xbc2>>>x.d[1].foo酒吧我认为,如果没有递归,这是不可能的,但是为 dicts 获取对象样式的好方法是什么?
更新: 在 Python 2.6 及以后,考虑 namedtuple
数据结构适合您的需求:
替代方案(原答案内容)是:
类结构:def __init__(self, **entries):self.__dict__.update(条目)
然后,您可以使用:
>>>args = {'a': 1, 'b': 2}>>>s = 结构(**参数)>>>秒<__main__.Struct 实例在 0x01D6A738>>>>s.a1>>>sb2I'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:
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
Should be accessible in this way:
>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
bar
I think, this is not possible without recursion, but what would be a nice way to get an object style for dicts?
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 "<stdin>", line 1, in <module>
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
这篇关于将嵌套的 Python dict 转换为对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!