Reputation: 31
How do I dump dictionary data into an excel file? I am missing price data in output.
import xlsxwriter
workbook = xlsxwriter.Workbook('myfile.xlsx')
worksheet = workbook.add_worksheet()
row = 0
col = 0
crypto_price={'BTC': {'GBP': 39552.11}, 'ETH': {'GBP': 2639.38}, 'BNB': {'GBP': 321.8}, 'ADA':
{'GBP': 1.665}, 'XRP': {'GBP': 0.7839}, 'SOL': {'GBP': 114.58}, 'DOT': {'GBP': 24.86}, 'DOGE':
{'GBP': 0.1776}, 'UNI': {'GBP': 18.72}, 'AVAX': {'GBP': 44.54}}
order=sorted(crypto_price.keys())
for key in order:
row += 1
print(key)
worksheet.write(row, col, key)
for item in crypto_price[key]:
print(item,row, col+1)
worksheet.write(row, col + 1, item)
col += 1
col = 0
workbook.close()
Upvotes: 1
Views: 140
Reputation: 496
There's a couple of problems in your code. You aren't getting the price because for item in crypto_price[key]:
only returns the key for the nested dict. In addtion, you close the workbook too early. So to simplify, you could do:
import xlsxwriter
workbook = xlsxwriter.Workbook('myfile.xlsx')
worksheet = workbook.add_worksheet()
row = 0
crypto_price={'BTC': {'GBP': 39552.11}, 'ETH': {'GBP': 2639.38}, 'BNB': {'GBP': 321.8}, 'ADA':
{'GBP': 1.665}, 'XRP': {'GBP': 0.7839}, 'SOL': {'GBP': 114.58}, 'DOT': {'GBP': 24.86}, 'DOGE':
{'GBP': 0.1776}, 'UNI': {'GBP': 18.72}, 'AVAX': {'GBP': 44.54}}
order=sorted(crypto_price.keys())
for key in order:
for innerkey, value in crypto_price[key].items():
worksheet.write(row, 0, key)
worksheet.write(row, 1, innerkey)
worksheet.write(row, 2, value)
row += 1
workbook.close()
Upvotes: 3