我是python新手,我打算对一个名为“用python自动化无聊的东西”的项目(从电子表格中读取数据,第12章“使用excel”)进行一些修改。一旦完成这个项目,我想把以前得到的词典印在同一本书的新页上。 但是现在,当我试图在excel表格中写作时,嵌套字典遇到了一些问题。代码在嵌套循环的第二行崩溃,所以我认为同样的情况也会发生在循环的netx行中
import openpyxl, pprint
libro=openpyxl.load_workbook(r"J:Pathtothedata\censuspopdata.xlsx")
hoja = libro.active
countyData={}
print('Reading rows...')
for row in range(2, hoja.max_row + 1):
# Each row in the spreadsheet has data for one census tract.
state = hoja['B' + str(row)].value
county = hoja['C' + str(row)].value
pop = hoja['D' + str(row)].value
countyData.setdefault(state,{})
countyData[state].setdefault(county, {'tracts': 0, 'pop': 0})
countyData[state][county]['tracts'] += 1
countyData[state][county]['pop'] += int(pop)
print('Writing results...')
libro.create_sheet(index=1,title='Subtotal')#Create a new worksheet
hoja1 = libro.worksheets[1]#set that sheet as active
#Here starts the problems
next_row = 1
for key, value in countyData.items():#for each element in allCounty print the results
for pop, tracts in value.items():
hoja1.cell(column=1,row=next_row,value=key)
hoja1.cell(column=2,row=next_row,value=value)
hoja1.cell(column=3,row=next_row,value=pop)
hoja1.cell(column=3,row=next_row,value=tracts)
next_row+=1
libro.save
我试着换第二行 hoja1.cell(列=2,行=下一行,值=值)到:
hoja1.cell(column=2,row=next_row,value=countyData[key])
不起作用。 它向我展示了带有图例“raisevalueerror”(“Cannot convert{0!r} 到Excel“。格式(值))”
然后我试着: hoja1.cell(column=2,row=next_row,value=countyData.get(key))并显示:
hoja1.cell(column=3,row=next_row,value=value.get(pop)
^
SyntaxError: invalid syntax
我希望输出像
字典中每个值的“州”“县”“人口”“域”
目前没有回答
相关问题 更多 >
编程相关推荐