Reputation: 335
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)
Upvotes: 0
Views: 1527
Reputation: 43
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
Upvotes: 0
Reputation: 82765
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
Upvotes: 2