Search code examples
pythonxlsxxlsxwriter

write python list within a dict to excel


import pprint
import xlsxwriter


def createDict():

people1 = {'name': 'John', 'age': '27', 'sex': 'Male', 'client': [
    {'name': 'Jamie', 'age': '22', 'sex': 'Male'}, {'name': 'Holly', 'age': '22', 'sex': 'Female'}]}
people2 = {'name': 'Marie', 'age': '22', 'sex': 'Female'}


workbook = xlsxwriter.Workbook('myfile.xlsx')
worksheet = workbook.add_worksheet()

row = 0
col = 0

for key in people1:
    row += 1
    # prints the keys for dicts
    worksheet.write(row, col, key)
    # prints the value for people 1
    worksheet.write(row, col + 1, people1[key])



# workbook.close()


createDict()

I have this code above and I am trying to print people1 results like below:

name: John
age : 27
sex : male
client: name: jamie
    age: 22
    sex:male
    name: holly
    age: 22
    sex:female

However, I keep getting this error:

TypeError: Unsupported type <class 'list'> in write()

Because it's a list.. please help. This is a small part of my dictionary and in some cases, I may have much larger data coming through but the concept will be the same.


Solution

  • recursive func?

    class ExcelWriter:
    
        row = 0
    
        def write_to_excel(self, value, col=0):
            if isinstance(value, dict):
                for k, v in value.items():
                    self.write_to_excel(k, col)
                    self.write_to_excel(v, col+1)
                    self.row += 1
            elif isinstance(value, list):
                for item in value:
                    self.write_to_excel(item, col)
                    self.row += 1
            else:
                worksheet.write(row, col, value)
    
    ExcelWriter().write_to_excel(people1)