【发布时间】: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