递归词典列表等的字典(python) [英] recursing a dictionary of lists of dictionaries, etc et al (python)

查看:105
本文介绍了递归词典列表等的字典(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从Yaml配置文件返回的字典,该字典具有4个级别:

I have a dictionary returned from a yaml configuration file with 4 levels:

项目,部分,字段,元素

item, sections, fields, elements

{
    "tag": "test", 
    "sections": [
        {
            "info": "This is section ONE", 
            "tag": "s1"
        }, 
        {
            "info": "This is section TWO", 
            "fields": [
                {
                    "info": "This is field ONE", 
                    "tag": "f1"
                }, 
                {
                    "info": "This is field TWO", 
                    "tag": "f2", 
                    "elements": [
                        {
                            "info": "This is element", 
                            "tag": "e1", 
                            "type_of": "text_field"
                        }, 
                        {
                            "info": "This is element", 
                            "tag": "e2", 
                            "type_of": "text_field"
                        }, 
                        {
                            "info": "This is element", 
                            "tag": "e3", 
                            "type_of": "text_field"
                        }, 
                        {
                            "info": "This is element", 
                            "tag": "e4", 
                            "type_of": "text_field"
                        }
                    ]
                }, 
                {
                    "info": "This is field THREE", 
                    "tag": "f3", 
                    "elements": [
                        {
                            "info": "This is element", 
                            "tag": "e5", 
                            "type_of": "text_field"
                        }, 
                        {
                            "info": "This is element", 
                            "tag": "e6", 
                            "type_of": "text_field"
                        }, 
                        {
                            "info": "This is element", 
                            "tag": "e7", 
                            "type_of": "text_field"
                        }, 
                        {
                            "info": "This is element ONE", 
                            "tag": "e8", 
                            "type_of": "text_field"
                        }
                    ]
                }
            ], 
            "tag": "s2"
        }, 
        {
            "info": "This is section THREE", 
            "fields": [
                {
                    "info": "This is field FOUR", 
                    "tag": "f4"
                }, 
                {
                    "info": "This is field FIVE", 
                    "tag": "f5"
                }, 
                {
                    "info": "This is field SIX", 
                    "tag": "f6"
                }
            ], 
            "tag": "s3"
        }
    ],
    "type_of": "custom"
}

class T():

    def __init__(self):
        self.sections = []
        self.fields = []
        self.elements = []

def rt(y):
    t = T()

    def recurse(y):
        for k,v in y.iteritems(): 
            if isinstance(v, list):
                getattr(t, k).append(v)
                [recurse(i) for i in v]
            else:
                setattr(t, k, v)
    recurse(y)
    return t

因此,我需要递归字典列表的字典,其中包含字典列表等.等,将它们分类为它们的类型(然后添加对它所属的块的引用,但是一次添加一个问题.),然后将其放入T的实例中.

So I need to recurse a dictionary of lists of dictionaries that have lists of dictionaries, et. al., sort them into their types (and then add a reference to the piece it belongs to, but one problem at a time.) and put into an instance of T.

这有效,但不进行任何修剪,即捕获了每个部分,但捕获了所有其余部分(字段,元素).这可能是sci 101,但我主要是在自学,因此我需要学习某种排序算法.任何有关改进此建议的意见.

This works, but doesn't trim out anything, i.e. each section is captured, but all the rest (fields, elements) are captured. This probably comp sci 101, but I'm mostly teaching myself so this some sort of sorting algorithm I need to learn about. Any input on improving this appreciated.

事实证明,这比我预期的要深入,并且抽象地讲,它是更多的机会来学习如何遍历任意数据结构并挑选出我想要的或需要的东西

This turned out to be more in depth than I expected, and is abstractly more of an opportunity to learn how to walk through arbitrary data structures and pick out what I want or need

推荐答案

我想到的解决方案:

class Tree:
    def __init__(self, node, cargo, parent=None):
        self.node = node
        self.cargo = cargo
        self.parent  = parent
    def __str__(self):
        return str(self.cargo)

from copy import copy
def just_part(y):
    z = copy(y)
    for k,v in z.items():
        if isinstance(v, list):
            del z[k]
    return z

def rt(y):
    tt = []
    s = Tree( id(y), just_part(y) )
    tt.append(s)
    def recurse(y):
        for k,v in y.iteritems(): 
            if isinstance(v, list):
                [tt.append( Tree(id(i), just_part(i), id(y) ) ) for i in v]
                [recurse(i) for i in v]
            else:
                pass
    recurse(y)
    return tt

我只运行rt(我的嵌套字典),这将返回一个节点列表,到目前为止,这似乎已经足以作为我正在做的事情的起点,而且我知道它可以以更有效的方式完成.存在以下内容: http://code.activestate.com/recipes/577982-recursively-walk-python-objects/,但它并不能解决所有问题,而我自己的解决方案可能不是目前使用最多的pythonic工具.

I just run rt(my nested dictionary), this returns a list of nodes which so far seems to be adequate a start for what I'm doing, and I know it can accomplished in a much more effective way. There is this: http://code.activestate.com/recipes/577982-recursively-walk-python-objects/ too, but it doesn't get at everything while my own solution maybe not the most pythonic works for now.

这篇关于递归词典列表等的字典(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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