我有一个 Python 脚本,它返回一个字典,我想将它存储在某个地方以用于更大的项目(脚本运行速度很慢,所以我不想每次需要字典时都只导入脚本) .
字典很小,所以我看到两个选项。我可以:
- 将字典保存到 pickle 文件
将字典作为文字写入新的 .py 文件,如下所示:
my_dict = slow_func() with open('stored_dict.py', 'w') as py_file: file_contents = 'stored_dict = ' + str(my_dict) py_file.write(my_dict)然后我可以使用
from stored_dict import stored_dict 访问字典文字
我应该选择这些选项之一吗?
请您参考如下方法:
Python 字典的实现类似于json。您可以使用 json 模块将 dict 转储到文件中,然后轻松将其加载回来:
import json
d = {1: 'a', 2: 'b', 3: 'c'}
with open('C:\temp.txt', 'w') as file:
json.dump(d, file)
with open('C:\temp.txt', 'r') as file:
new_d = json.load(file)
>>> new_d
{u'1': u'a', u'3': u'c', u'2': u'b'}
