Home » excel » excel – Write Python dictionary to file

excel – Write Python dictionary to file

Posted by: admin May 14, 2020 Leave a comment


I’ve been trying to understand how to work with Website APIs and how to use get methods to download data from the website.

At the moment I have a big dictionary that I’m trying to write to file.

When I output it to a file it looks like this:

 {"Tickets":[{"Project":"Test_Project", "TicketID":"1", "Title":"Title_1", "Reportedby":"User_1"},{"Project":"Test_Project", "TicketID":"2", "Title":"Title_2", "Reportedby":"User_2"}]}

How can I output this to a Excel file?

I’ve tried using all kinds of string formatting, like:

response_string = response_string[response_string.find("["):len(response_string)-1]
response_string = response_string[1:len(response_string)-1]
response_string = response_string.replace("},{","} , {")
response_array = response_string.split(" , ") + response_array

but I know this is not the right way as a comma inside of the text would really mess this up.


How to&Answers:

If you want to save a dictionary to a csv file, the basic method is to use the csv module. The assumption is that you have a list of dictionaries, with keys as the column names and values you want to save.

import csv

data = {"Tickets":[{"Project":"Test_Project", "TicketID":"1", "Title":"Title_1", "Reportedby":"User_1"},{"Project":"Test_Project", "TicketID":"2", "Title":"Title_2", "Reportedby":"User_2"}]}

#Write a CSV file. 
f = open('temp','w')
c = csv.DictWriter(f,data['Tickets'][0].keys())

#Read a CSV file. 
f = open('temp','r')
c = csv.DictReader(f)
data = {'Tickets':list(c)}


A much easier way to save dictionaries or any other files is joblib from sklearn.externals.

You can do this there in a single line.

joblib.dump('filename', dict_name)