将嵌套的Pythondict转换为对象?

将嵌套的Pythondict转换为对象?

我正在寻找一种优雅的方法来使用属性访问DECT来获取数据,其中包含一些嵌套的DECTS和列表(即javascript样式的对象语法)。

例如:

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

应以这种方式获得:

>>> x = dict2obj(d)>>> x.a1>>> x.b.c2>>> x.d[1].foo
bar

我认为,如果没有递归,这是不可能的,但是有什么好的方法来获得DECTS的对象样式呢?


交互式爱情
浏览 1221回答 3
3回答

慕尼黑5688855

在Python2.6和更高版本中,请考虑namedtuple数据结构适合您的需要:>>> from collections import namedtuple>>> MyStruct = namedtuple('MyStruct', 'a b d')>>> s = MyStruct(a=1, b={'c': 2}, d=['hi'])>>> sMyStruct(a=1, b={'c': 2}, d=['hi'])>>> s.a1>>> s.b{'c': 2}>>> s.cTraceback (most recent call last):&nbsp; File "<stdin>", line 1, in <module>AttributeError: 'MyStruct' object has no attribute 'c'>>> s.d['hi']备选方案(最初的答复内容)是:class Struct:&nbsp; &nbsp; def __init__(self, **entries):&nbsp; &nbsp; &nbsp; &nbsp; self.__dict__.update(entries)然后,您可以使用:>>> args = {'a': 1, 'b': 2}>>> s = Struct(**args)>>> s<__main__.Struct instance at 0x01D6A738>>>> s.a1>>> s.b2

忽然笑

class&nbsp;obj(object): &nbsp;&nbsp;&nbsp;&nbsp;def&nbsp;__init__(self,&nbsp;d): &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;a,&nbsp;b&nbsp;in&nbsp;d.items(): &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;isinstance(b,&nbsp;(list,&nbsp;tuple)): &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setattr(self,&nbsp;a,&nbsp;[obj(x)&nbsp;if&nbsp;isinstance(x,&nbsp;dict)&nbsp;else&nbsp;x&nbsp;for&nbsp;x&nbsp;in&nbsp;b]) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;else: setattr(self,&nbsp;a,&nbsp;obj(b)&nbsp;if&nbsp;isinstance(b,&nbsp;dict)&nbsp;else&nbsp;b)>>>&nbsp;d&nbsp;=&nbsp;{'a':&nbsp;1,&nbsp;'b':&nbsp;{'c':&nbsp;2},&nbsp;'d':&nbsp;["hi",&nbsp;{'foo':&nbsp;"bar"}]}>>>&nbsp;x&nbsp;=&nbsp;obj(d)>>> &nbsp;x.b.c2>>>&nbsp;x.d[1].foo'bar'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python