我想保存python的一个dict文件到本地,有没有什么不依赖包版本的保存方式
- User
我想保存python的一个dict文件到本地,有没有什么不依赖包版本的保存方式
Assistant
有几种不依赖外部包的方式可以保存Python字典到本地:
1. 使用pickle(推荐)
import pickle # 保存 data = {'key1': 'value1', 'key2': [1, 2, 3]} with open('data.pkl', 'wb') as f: pickle.dump(data, f) # 读取 with open('data.pkl', 'rb') as f: loaded_data = pickle.load(f)2. 使用json(适合简单数据类型)
import json # 保存 data = {'key1': 'value1', 'key2': [1, 2, 3]} with open('data.json', 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) # 读取 with open('data.json', 'r', encoding='utf-8') as f: loaded_data = json.load(f)3. 使用repr/eval(简单但有安全风险)
# 保存 data = {'key1': 'value1', 'key2': [1, 2, 3]} with open('data.txt', 'w') as f: f.write(repr(data)) # 读取(注意:eval有安全风险,只用于可信数据) with open('data.txt', 'r') as f: loaded_data = eval(f.read())推荐使用pickle,因为它是Python标准库的一部分,支持几乎所有Python对象类型,且不依赖外部包版本。如果你的字典只包含基本数据类型(字符串、数字、列表、字典),json也是很好的选择,因为它生成的文件可读性更好。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.