如何将python字典写入excel文件?

时间:2016-08-19 15:40:52

标签: python excel dictionary

我正在尝试将随机生成的字符串和数字的字典写入excel文件。我几乎成功但有一个小问题。我字典的结构如下:

Age: 11, Names Count: 3, Names: nizbh,xyovj,clier

该词典是通过文本文件获得的数据生成的。它根据年龄汇总所有内容,如果两个人的年龄相同,则将它们分组到一个列表中。我正在尝试将此数据写入excel文件。到目前为止,我已经编写了这段代码。

import xlsxwriter
lines = []

workbook = xlsxwriter.Workbook('demo.xlsx')
worksheet = workbook.add_worksheet()

with open ("input2.txt") as input_fd:
    lines = input_fd.readlines()

age_and_names = {}

for line in lines:
    name,age = line.strip().split(",")


    if not age in age_and_names:
        age_and_names[age]=[]

    age_and_names[age].append(name)

print age_and_names

for key in sorted(age_and_names): 
    print "Age: {}, Names Count: {}, Names: {}".format(key, len(age_and_names[key]), ",".join(age_and_names[key]))

row=0
col=0

for key in sorted(age_and_names):#.keys():
    row += 1
    worksheet.write(row, col, key)

    for item in age_and_names[key]:
        worksheet.write(row, col+1, len(age_and_names[key]))
        worksheet.write(row, col+1, item)
        row+=1 

workbook.close()  

但实际上这是在(在excel文件中):

11    nizbh
      xyovj
      clier

我该怎么办才能让它看起来像这样呢?

Age   Name Count         Names 
11        3        nizbh, xyovj, clier

1 个答案:

答案 0 :(得分:2)

问题确实存在于两个for循环中。我干涉并和他们一起玩,直到我到达答案。他们工作正常。谢谢你们!

最后用以下代码替换for循环:

for key in sorted(age_and_names):#.keys():
    row+=1
    worksheet.write(row, col, key)
    worksheet.write(row, col+1, len(age_and_names[key]))
    worksheet.write(row, col+2, ",".join(age_and_names[key]))