将Python dict转换为对象? [英] Convert Python dict to object?
本文介绍了将Python dict转换为对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种优雅的方法来将普通的Python dict与一些嵌套的dict转换成一个对象。例如:
>>> d = {'a':1,'b':{'c':2},'d':[hi,{'foo':bar}}}
应该可以这样访问:
>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> xd [1] .foo
bar
我认为,这不可能没有递归,但是,为了获得对象的目标,会有什么好的方式?
提前谢谢。
解决方案
更新:在Python 2.6及以上版本中,请考虑 namedtuple
数据结构符合您的需求:
>>>从集合导入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
追溯(最近的最后一次调用):
文件< stdin>,第1行,< module>
AttributeError:'MyStruct'对象没有属性'c'
>>> sd
['hi']
替代(原始答案内容)是: p>
class Struct:
def __init __(self,** entries):
self .__ dict __。update )
然后,您可以使用:
>>> args = {'a':1,'b':2}
>>> s = Struct(** args)
>>>> s
< __ main __。结构实例在0x01D6A738>
>>> s.a
1
>>> s.b
2
I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.
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 objectstyle for dicts?
Thank you in advance.
解决方案
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转换为对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文