-3

Below is my sample dictionary.

dict1 = {'X':[['a','1'], ['b','3'], ['c','2']],
         'Y':[['a','8'], ['b','13']],
         'Z':[['a','5'], ['b','7'], ['f','8']]}

I am trying to get the below output in excel sheet using xlwt module.

X    a       1
     b       3
     c       2

Y    a       8
     b      13

Z    a       5
     b       7
     f       8
DeepSpace
  • 78,697
  • 11
  • 109
  • 154

1 Answers1

1

dict1 won't preserve its order when writing the keys/values to the excel file, but one option may be to put the contents in an OrderedDict then write each entry to rows, columns in the excel file:

import collections
# save order in dict1 to OrderedDict 
od = collections.OrderedDict(sorted(d.items(), key=lambda t: t[0]))

row = 0
for key in od.iterkeys():
    # write the key
    sheet.write(row, 0, key)
    for values in od[key]:
        for column, value in enumerate(values):
        # write each of this key's values in this row's columns    
        sheet.write(row, column+1, value)
        row += 1

Other than blank lines between the keys, it appears to match your desired output: enter image description here