【问题标题】:python dynamic dictionarypython动态字典
【发布时间】:2011-06-02 23:19:40
【问题描述】:

我正在创建一个处理 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

我的问题是,有没有一种方法可以动态地进行此操作,而不必为每一级数据创建循环?

【问题讨论】:

  • 我想过,但我想映射所有数据以便快速访问,所以我只想使用字典
  • 在最新版本的 Python 中,也有字典推导:sub_info = {i.tag: i.text for i in tag}

标签: python dictionary for-loop


【解决方案1】:

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

在最新版本的 Python 中,有字典推导式和列表推导式。像这样:

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

【讨论】:

  • 对于较旧的python版本:dict(((i.tag, i.text) for i in tag))
猜你喜欢
  • 1970-01-01
  • 2013-04-28
  • 2015-03-18
  • 2016-05-23
  • 2018-06-02
  • 2021-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多