Problems with iteration in dict with using xlsxwriter

Viewed 97

Good time a day. I Have got a dict. I need to save it in excel in such format. I imported xlsxwriter and try to save result with using for. And got an error. Could anybody help me to improve an error? I will bless you.

TypeError: 'int' object is not iterable

#This is dict

repack_values = {
    'rows':
        {1:
            {'area_id': 1, 'indicator_name_id': 4, 'area_name': 'Российская Федерация', 'indicator_name': 'Стоимость основных фондов в отрасли Обрабатывающие производства, млн. руб.', 2002: 7212776, 2003: 7709820, 2004: 8526843, 2005: 3641287, 2006: 4218012, 2007: 5122970, 2008: 6001501, 2009: 6984796, 2010: 7989040, 2011: 8876602, 2012: 9862265, 2013: 11378966, 2014: 13442626, 2015: 15099981, 2016: 16437831, 2017: 18956787},
         2:
            {'area_id': 2, 'indicator_name_id': 4, 'area_name': 'Центральный федеральный округ', 'indicator_name': 'Стоимость основных фондов в отрасли Обрабатывающие производства, млн. руб.', 2002: 1278063, 2003: 1324242, 2004: 1465904, 2005: 966375, 2006: 1153337, 2007: 1441097, 2008: 1715997, 2009: 2038715, 2010: 2358551, 2011: 2458690, 2012: 2652592, 2013: 3045705, 2014: 3415095, 2015: 3821452, 2016: 4219281, 2017: 4750780}},
                 'years': [2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017]
                 }

#The end of dict

""" Writing to excel """

import xlsxwriter
excel_doc = 'result.xlsx'
workbook = xlsxwriter.Workbook(excel_doc)
worksheet = workbook.add_worksheet()
col_num = 0
for area_id, row in repack_values['rows'].items():
    worksheet.write(0, col_num, row['area_name'])
    for year in repack_values['years']:
        worksheet.write_column(1, col_num, row.get(year))
1 Answers

Considering desired output from your screenshot :

# Write headers
worksheet.write(0, 0, "xyz") # enter your text from image for Column=0,Row=0
worksheet.write_row(0, 1, repack_values['years'])

for area_id, row in repack_values['rows'].items():
    worksheet.write(area_id, col_num, row['area_name'])
    worksheet.write_row(area_id, 1, [row[year] for year in repack_values['years']])
workbook.close()

This will create excel in the required format. format

Related