Save a dictionary to a file

本文介绍了如何将Python字典保存为不同格式的文件,包括CSV、JSON、纯文本及Pickle文件等。此外还提到了可以使用SQLite数据库来存储字典数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Save a dictionary to a file

Given a dictionary such as:

dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}

We can save it to one of these formats:

  • Comma seperated value file (.csv)
  • Json file (.json)
  • Text file (.txt)
  • Pickle file (.pkl)

You could also write to a SQLite database.
https://pythonspot.com/python-database-programming-sqlite-tutorial/

1. save dictionary as csv file

we can write it to a file with the csv module.

import csv

dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}
w = csv.writer(open("output.csv", "w"))
for key, val in dict.items():
    w.writerow([key, val])

在这里插入图片描述

The dictionary file (csv) can be opened in Google Docs or Excel

2. save dictionary to json file

If you want to save a dictionary to a json file

import json

dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}

json = json.dumps(dict)
f = open("dict.json","w")
f.write(json)
f.close()

3. save dictionary to text file (raw, .txt)

You can save your dictionary to a text file using the code below:

dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}
f = open("dict.txt","w")
f.write( str(dict) )
f.close()

4. save dictionary to a pickle file (.pkl)

The pickle module may be used to save dictionaries (or other objects) to a file. The module can serialize and deserialize Python objects.
该模块可以序列化和反序列化 Python 对象。

serialize [ˈsɪərɪəlaɪz]:vt. 连载,使连续
deserialize:vt. 并行化,串并转换
import pickle
dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}
f = open("file.pkl","wb")
pickle.dump(dict,f)
f.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值