Alin G.
Alin G.

Reputation: 45

Write Python dictionary to file

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.

Thanks, A.

Upvotes: 1

Views: 476

Answers (2)

Abhishek Verma
Abhishek Verma

Reputation: 1729

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)

https://scikit-learn.org/stable/modules/model_persistence.html

Upvotes: 1

Bobby Ocean
Bobby Ocean

Reputation: 3328

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())
c.writeheader()
c.writerows(data['Tickets'])
f.close()

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

Upvotes: 2

Related Questions