简体   繁体   English

将 Python 字典写入文件

[英]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.我一直在尝试了解如何使用网站 API 以及如何使用 get 方法从网站下载数据。

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:当我将 output 放到一个文件中时,它看起来像这样:

 {"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?我怎样才能将 output 转换为 Excel 文件?

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.谢谢。

If you want to save a dictionary to a csv file, the basic method is to use the csv module.如果要将字典保存到 csv 文件中,基本方法是使用 csv 模块。 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()

A much easier way to save dictionaries or any other files is joblib from sklearn.externals.保存字典或任何其他文件的更简单的方法是来自 sklearn.externals 的 joblib。

You can do this there in a single line.您可以在一行中执行此操作。

joblib.dump('filename', dict_name)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM