Create excel from a list that has a dictionary inside

1

I would like to know how to create an Excel file with the data inside a list that has dictionaries nested in Python.

The structure of the data is as follows:

xs=[{'x': 2, 'y': 1, 'z': 4}, {'x': 3, 'y': 15, 'z': 41}, {'x': 22, 'y': 10, 'z': 40}, {'x': 132, 'y': 89, 'z': 01}]

I'm using the xlsxwriter library but I have a question about how to iterate to get each dictionary to be a row, with each key being a column.

That is, the previous list should give rise to the following table:

┌─────┬────┬────┐
│   2 |  1 │  4 │
├─────┼────┼────┤
│   3 │ 15 │ 41 │
├─────┼────┼────│
│  22 │ 10 │ 40 │
├─────┼────┼────┤
│ 132 │ 89 │  1 │ 
└─────┴────┴────┘
    
asked by David Gomez García 25.08.2017 в 02:29
source

1 answer

1

The problem is basically that by having a normal dictionary, the order is not preserved. For each piece of data to be in the appropriate cell you must use two for and some structure to define the order of each column.

One possible solution is to use a list next to enumerate :

import xlsxwriter

xs = [{'x': 2,   'y': 1,  'z': 4}, 
      {'x': 3,   'y': 15, 'z': 41},
      {'x': 22,  'y': 10, 'z': 40},
      {'x': 132, 'y': 89, 'z': 1}]

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

headers = ['x', 'y', 'z']

for row, _dict in enumerate(xs):
    for col, key in enumerate(headers):
        worksheet.write(row, col, _dict[key])
workbook.close()

Exit:

    
answered by 25.08.2017 / 04:07
source