我有python词典:
student_age = {'bala':20,'raju':21}
student_id = {'bala':289,'raju':567}
以及十个类似的词典,其中键作为学生姓名和价值不同的字段。
而不是
worksheet.write(0,2,20)
我想根据学生的名字写作,如写(“bala” - >“年龄”,20)
更新代码:
import xlsxwriter
workbook = xlsxwriter.Workbook('student_data.xlsx')
worksheet = workbook.add_worksheet()
student_age={'bala':20,'raju':21,'ram':22}
student_id={'bala':289,'ram':567,'raju':654}
students = student_id.keys()
print(len(student_age.keys()))
fields = [student_age, student_id] # add other dicts here...
for row, student in enumerate(students):
worksheet.write(row, 0, student) # name column
for col, student_data in enumerate(fields):
col = col + 1
worksheet.write(row, col, student_data[student])
workbook.close()
上述代码工作正常,但存在以下争议:
答案 0 :(得分:1)
您可以简单地将所有python词典添加到列表中,这样您就可以为每个学生迭代它们以填充每一行的每一列。像这样:
已更新,以解决OP的评论
对于#1,只需在第一行中写入标题,然后将其他行偏移一个
对于#2,如果id不在该字典中,您可以简单地利用dict.get()
而不是[]
表示法来指定默认值:
import xlsxwriter
workbook = xlsxwriter.Workbook('student_data.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': 1})
students = student_id.keys()
fields = [student_age, student_id] # add other dicts here...
headers = ['name', 'age', 'id'] # ...
# write out a header row
for i, header in enumerate(headers):
worksheet.write(0, i, header, bold)
for row, student in enumerate(student):
row = row + 1
worksheet.write(row, 0, student) # name column
for col, student_data in enumerate(fields):
col = col + 1
worksheet.write(row, col, student_data.get(student, ''))
答案 1 :(得分:0)
检查此链接以了解python中的词典:http://learnpythonthehardway.org/book/ex39.html
如果没有提供一些示例代码,很难看到你做了什么,所以请用示例代码编辑您的问题,我也会编辑我的答案。
你是否迭代正确地抛出你的词典并准确写入excel文件的行,列?