Django – Export List of dictionaries to CSV

Question:

I have created a list of dictionaries in views.py,

my_list= [
{'user': 1000, 'account1': 100, 'account2': 200, 'account3': 100},
{'user': 1001, 'account1': 110, 'account2': 100, 'account3': 250},
{'user': 1002, 'account1': 220, 'account2': 200, 'account3': 100},
]

I want to export it to csv file.

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="mylist.csv"'

    writer = csv.writer(response)
    for data in my_list:
        writer.writerow(data)

    return response

I know there is a error for “for data in my_list”.
my_list contains all the keys and values.

How to get only keys for my_list? or there is another method to export list to csv?

(I’m using django 2 with python3.4)

Asked By: user3114168

||

Answers:

You need DictWriter

Demo:

import csv
my_list= [
{'user': 1000, 'account1': 100, 'account2': 200, 'account3': 100},
{'user': 1001, 'account1': 110, 'account2': 100, 'account3': 250},
{'user': 1002, 'account1': 220, 'account2': 200, 'account3': 100},
]

with open(filename, "w") as infile:
    writer = csv.DictWriter(infile, fieldnames=my_list[0].keys())
    writer.writeheader()
    for data in my_list:
        writer.writerow(data)

with open(filename, 'rb') as infile:
    response = HttpResponse(infile, content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=mylist.csv'
    return response
Answered By: Rakesh

You can use DictWriter as follows:

my_list= [
    {'user': 1000, 'account1': 100, 'account2': 200, 'account3': 100},
    {'user': 1001, 'account1': 110, 'account2': 100, 'account3': 250},
    {'user': 1002, 'account1': 220, 'account2': 200, 'account3': 100},
]

response = HttpResponse(content_type="text/csv")
response["Content-Disposition"] = "attachment; filename=my_list.csv"

# writing to csv with DictWriter
writer = csv.DictWriter(response, fieldnames=my_list[0].keys())
writer.writeheader()
writer.writerows(my_list)

return response
Answered By: Ramesh Pradhan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.