How do I output a list of dictionaries to an Excel sheet?

dictionary, excel, file-io, list, python

Solution

test.py

from csv import DictWriter

players = [{'dailyWinners': 3, 'dailyFreePlayed': 2, 'user': 'Player1', 'bank': 0.06},
{'dailyWinners': 3, 'dailyFreePlayed': 2, 'user': 'Player2', 'bank': 4.0},
{'dailyWinners': 1, 'dailyFree': 2, 'user': 'Player3', 'bank': 3.1},            
{'dailyWinners': 3, 'dailyFree': 2, 'user': 'Player4', 'bank': 0.32}]

with open('spreadsheet.csv','w') as outfile:
    writer = DictWriter(outfile, ('dailyWinners','dailyFreePlayed','dailyFree','user','bank'))
    writer.writeheader()
    writer.writerows(players)

Run `python test.py`

Then open the resulting `spreadsheet.csv` file in Excel.

NOTE: I'm running Linux so I wasn't able to test this using Microsoft Excel. This works in LibreOffice Calc and gives a spreadsheet where the keys are the column names and the values are under their appropriate columns.

Problem

I have a list called 'players' that consists of dictionaries. It looks like this: ``` players = [{'dailyWinners': 3, 'dailyFreePlayed': 2, 'user': 'Player1', 'bank': 0.06}, {'dailyWinners': 3, 'dailyFreePlayed': 2, 'user': 'Player2', 'bank': 4.0}, {'dailyWinners': 1, 'dailyFree': 2, 'user': 'Player3', 'bank': 3.1}, {'dailyWinners': 3, 'dailyFree': 2, 'user': 'Player4', 'bank': 0.32}] ``` It's much longer, but this is an excerpt. How do I output this list of dictionaries to an Excel file so it's neatly organized by key/value?

Original source