我有一个Python脚本,返回一个字典,我想将其存储在某个地方以便在更大的项目中使用(该脚本运行缓慢,因此我不想每次需要字典时都导入脚本)。
这个字典很小,所以我看到两个选择。我可以:
- Save the dict to a pickle file
Write the dict as a literal to a new .py file, like so:
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)
Then I can access the dict literal using
from stored_dict import stored_dict
我应该偏好这些选项中的哪一个?
JSON
文件中,这个文件看起来和字典一样。 - Chen A.