python - 复杂地将嵌套字典转换为python中的对象

标签 python

开始学习python时间不长,但很想深入挖掘一下。并努力挖掘。所以这是我研究了一段时间但还没有破解的任务:
我得到了嵌套字典和列表的混合组合(我们称它为“组合”),我需要实现函数以允许将嵌套元素作为对象属性进行访问,也以某种方式将 combination 元素视为可迭代的。这应该看起来像这样:

combination = {
'item1': 3.14,
'item2': 42,
'items': [
         'text text text',
         {
             'field1': 'a',
             'field2': 'b',
         },
         {
             'field1': 'c',
             'field2': 'd',
         },
         ]
}

def function(combination):
    ...

这样
列表(函数(组合).items.field1) 将给出:['a', 'c']
list(function(combination).item1) 将给出:[3.14]
编辑 正如@FM 所提到的,我错过了处理非字典元素的描述: list(function(combination).items[0]) >>> ['text text text']


我尝试实现一个类(感谢 Marc)来帮助我:

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

然后在函数中使用它,比如return Struct(**combination)
虽然非常漂亮,但这只是达到预期结果的第一步。
但由于下一步需要更深入,它让我不知所措,我无法独自完成。
因此,我恳请您的帮助。

迈克尔。

最佳答案

怎么样:

class ComboParser(object):
    def __init__(self,data):
        self.data=data
    def __getattr__(self,key):
        try:
            return ComboParser(self.data[key])
        except TypeError:
            result=[]
            for item in self.data:
                if key in item:
                    try:
                        result.append(item[key])
                    except TypeError: pass
            return ComboParser(result)
    def __getitem__(self,key):
        return ComboParser(self.data[key])
    def __iter__(self):
        if isinstance(self.data,basestring):
            # self.data might be a str or unicode object
            yield self.data
        else:
            # self.data might be a list or tuple
            try:
                for item in self.data:
                    yield item
            except TypeError:
                # self.data might be an int or float
                yield self.data
    def __length_hint__(self):
        return len(self.data)

产生:

combination = {
    'item1': 3.14,
    'item2': 42,
    'items': [
        'text text text',
        {
            'field1': 'a',
            'field2': 'b',
            },
        {
            'field1': 'c',
            'field2': 'd',
            },
        {
            'field1': 'e',
            'field3': 'f',
            },        
        ]
    }
print(list(ComboParser(combination).item1))
# [3.1400000000000001]
print(list(ComboParser(combination).items))
# ['text text text', {'field2': 'b', 'field1': 'a'}, {'field2': 'd', 'field1': 'c'}, {'field3': 'f', 'field1': 'e'}]
print(list(ComboParser(combination).items[0]))
# ['text text text']
print(list(ComboParser(combination).items.field1))
# ['a', 'c', 'e']

关于python - 复杂地将嵌套字典转换为python中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5290715/

相关文章:

python - 使用 Scoop 编程 DEAP

python - Django:没有名为设置的模块

python - TTK Notebook 在导入的选项卡之间共享数据

python - 为什么我不能使用 pdb 交互式调试器进入正在运行的测试?

python - 使用轮询而不是 websockets 的 Flask-SocketIO 服务器

Python - 为什么 <br> 在 Scrapy 中破坏 XPath text()?

python - 如何创建动态上传路径Django

python - 写入 3,795,790,711 唯一键 :value pairs to redis

python - 在 Django 中,我有一个复杂的查询,我只需要通过外键获取唯一值,这可能吗?

python - 后台运行python,需要先获取用户输入