5

I'm trying to write a dictionary with randomly generated strings and numbers to an excel file. I've 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 aggregates all the contents based on their age and if two people have the same age, it groups them into one list. I'm trying to write this data on to an excel file. I've written this piece of code so far.

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 is actually doing is this (in the excel file):

11 nizbh xyovj clier 

What should I do to make it appear like this instead?

Age Name Count Names 11 3 nizbh, xyovj, clier 
3
  • 1
    The problem is in your final two for loops. Step through those carefully in your head, or on paper, or by adding print statements to debug what you are actually writing to what row and column. Hint: you're overwriting the contents of some of the cells more than once. Commented Aug 19, 2016 at 15:50
  • Kudos @nekomatic for keeping it fun and challenging Commented Aug 19, 2016 at 16:06
  • Any other hints to print values in the same cell separated by commas? Everything else is good. Commented Aug 19, 2016 at 16:25

1 Answer 1

3

The problem was indeed in the two for loops there. I meddled and played around with them until I arrived at the answer. They're working fine. Thank you guys!

Replace the for loops in the end with this:

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])) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.