【问题标题】:Best way to store a large python dictionary in a file将大型 python 字典存储在文件中的最佳方法
【发布时间】:2012-08-17 05:10:01
【问题描述】:

我有一个生成大型 python 字典的 python 脚本(脚本 1)。这本字典必须由另一个脚本(脚本 2)读取。 任何人都可以建议我编写由脚本 1 生成并由脚本 2 读取的 python 字典的最佳方法。 过去我曾使用 cPickle 编写和阅读如此大的字典。 有没有更好的方法来做到这一点?

【问题讨论】:

  • “大字典”的另一个名称是“数据库”。

标签: python python-2.7


【解决方案1】:

shelve 将允许您分别访问每个项目,而不是要求您每次都序列化和反序列化整个字典。

【讨论】:

  • 搁置很好,只要所有的键都是字符串
  • @John La Rooy。如果键是字符串呢?
【解决方案2】:

如果您希望您的字典可以被不同类型的脚本(即不仅仅是 Python)读取,JSON 也是一个不错的选择。

它没有shelve 快,但它易于使用且人眼可读。


import json
with open("/tmp/test.json", "w") as out_handle:
    json.dump(my_dict, out_handle)  # save dictionary

with open("/tmp/test.json", "r") as in_handle:
    my_dict = json.load(in_handle)  # load dictionary

【讨论】:

  • 字典非常大,json可能会耗尽内存。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-19
  • 1970-01-01
  • 2015-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多