How to write python dictionary to excel file?

I am trying to write a dictionary with randomly generated strings and numbers to an excel file. I almost succeeded, but with one minor problem. The structure of my dictionary is as follows:

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

This dictionary was generated from data obtained through a text file. It combines all the content depending on their age, and if two people are the same age, he groups them into one list. I am trying to write this data to an excel file. I already wrote this piece of code.

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()  

But what this actually does is (in the excel file):

11    nizbh
      xyovj
      clier

What should I do to make it look like this?

Age   Name Count         Names 
11        3        nizbh, xyovj, clier
+4
source share
1 answer

. , . . , !

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]))
+2

Source: https://habr.com/ru/post/1651811/


All Articles