2

Hi have dictionary data as shown:

{'Count': 5, '_id': {'ele_id': ['17cd-4a9f-9671-80eda11f9c53'], 'day': '2015-09-22'}, 'name': 'Default Astn'}
{'Count': 2, '_id': {'ele_id': ['17cd-4a9f-9671-80eda11f9c53'], 'day': '2015-09-18'}, 'name': 'Default Astn'}
{'Count': 1, '_id': {'ele_id': ['ccdf-4e0b-a87c-4e7738a0ed33'], 'day': '2015-09-14'}, 'name': 'sharepoint Astn'}
{'Count': 1, '_id': {'ele_id': ['2b9f-436b-a2ff-c4bc4059a9c8'], 'day': '2015-09-14'}, 'name': 'JPL Astn'}
{'Count': 2, '_id': {'ele_id': ['17cd-4a9f-9671-80eda11f9c53'], 'day': '2015-09-14'}, 'name': 'Default Astn'}

Want to write to CSV with columns and data as below:

Date        Name           Count
2015-09-22  Default Astn     5
2015-09-18  Default Astn     2
2015-09-14  sharepoint Astn  1
            JPL Astn         1
            Default Astn     2

Problem I'm facing is for 3 row, just add 2 and 3rd column if 1st column is already same. My code is as below

with open('test.csv', 'wb') as f:
    fieldnames = ['Date','Name','Count']
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        for line in data:
            writer.writerow({'Date' : line['_id']['day'],'Name' : line['name'], 'Count':line['Count']})

1 Answer 1

1

Try this ..... haven't tested but I think the logic remains the same......

with open('test.csv', 'wb') as f:
fieldnames = ['Date','Name','Count']
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    prev_date = ''
    for line in data:
        curr_date = line['_id']['day']
        if curr_date == prev_date:
            writer.writerow({'Date' : '','Name' : line['name'], 'Count':line['Count']})
        else:
            writer.writerow({'Date' : curr_date,'Name' : line['name'], 'Count':line['Count']})
            prev_date = curr_date
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the logic it worked. Also with same respective is it possible increase the width of the each column when writing header .
@kittu It does work this way, it depends on the application(MS Excel, etc) with which you are opening your csv file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.