Python 动态字典

1 投票
1 回答
2634 浏览
提问于 2025-04-16 18:52

我正在创建一个处理XML数据的函数,这些数据可能会有所不同,但结构是一样的:

事件(像列表一样)
    事件
        信息
        附加信息

这个函数需要创建一个字典,字典里要有一个映射关系,如果正在循环的数据不为0,那么就需要把这些数据映射到字典里。以下是我的解决方案:

def parse_items(self, xml):
            """ Builds a dynamic dictionary tree wich holds each event in a dictionary
               that can be accessed by number of event """
            parsed_items = {}
            parsed_item = {}
            sub_info = {}
            for num, item in enumerate(xml):
                for tag in item:
                    if len(tag) != 0:
                        for info in tag:
                            sub_info[info.tag] = info.text
                        parsed_item[tag.tag] = sub_info
                        # Need to flush the dictionary else it will repeat info
                        sub_info = {}
                    else:
                        parsed_item[tag.tag] = tag.text
                parsed_items[num] = parsed_item
                # Need to flush the dictionary else it will repeat info
                parsed_item = {}
            return parsed_items

我的问题是,有没有办法让这个过程动态进行,而不需要为每一层数据都写一个循环?

1 个回答

3

(重新发布作为答案,因为提问者打算使用这个想法)

在最新版本的Python中,除了列表推导式,还有字典推导式。用法如下:

sub_info = {i.tag: i.text for i in tag}

撰写回答