Python – Extract resulted list data to a xml file in python


How can I extract my resulted list data to an xml file?

My resulted list is given below:

week=[{'item': Electrelane, 'weight': 140}, {'item': Kraftwerk, 'weight': 117},{'item': The Flaming Lips, 'weight': 113}]

Best Solution

Since you don't provide any information on how you want to format your XML, i just invented my own notation.

week=[{'item': 'Electrelane', 'weight': 140}, {'item': 'Kraftwerk', 'weight': 117},{'item': 'The Flaming Lips', 'weight': 113}]

print "<?xml version='1.0' ?>"
print "<week>"
for day in week:
    print "  <day>"
    for key, value in day.items():
        print "    <%s>%s</%s>" % (key, value, key)
    print "  </day>"
print "</week>"


To print to console, iterate over items in a similar way but change the output (by the print commands)

# enumerate the days in the week
for i, day in enumerate(week):
    print "day %d" % i
    # show values in sorted order
    for key in sorted(day):
        print "  - %s\t: %s" % (key, day[key])