im creating a function that will handle xml data, the data can vary but the structure is the same :
events ( list like ) event info additional info
the function needs to create a dictionary that contains a mapping in which if the data being looped is not 0 then the data needs to be mapped in a dictionary, heres my solution:
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_in开发者_高级运维fo = {}
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
my question is, is there a way to make this dynamically without having to make for loops for every level of data ?
(Reposting as an answer, because the questioner intends to use the idea)
In the latest versions of Python, there are dict comprehensions as well as list comprehensions. Like this:
sub_info = {i.tag: i.text for i in tag}
精彩评论