将嵌套的 Python dict 转换为对象? [英] Convert nested Python dict to object?

查看:55
本文介绍了将嵌套的 Python dict 转换为对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种优雅的方式来使用字典上的属性访问来获取数据,其中包含一些嵌套的字典和列表(即 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 数据结构适合您的需求:

<预><代码>>>>从集合导入namedtuple>>>MyStruct = namedtuple('MyStruct', 'a b d')>>>s = MyStruct(a=1, b={'c': 2}, d=['hi'])>>>秒MyStruct(a=1, b={'c': 2}, d=['hi'])>>>s.a1>>>sb{'c':2}>>>s.c回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中AttributeError: 'MyStruct' 对象没有属性 'c'>>>标准差['你好']

替代方案(原答案内容)是:

类结构:def __init__(self, **entries):self.__dict__.update(条目)

然后,您可以使用:

<预><代码>>>>args = {'a': 1, 'b': 2}>>>s = 结构(**参数)>>>秒<__main__.Struct 实例在 0x01D6A738>>>>s.a1>>>sb2

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:

>>> 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 转换为对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆