【问题标题】:How can I read a file that contains a list of dictionaries into python?如何将包含字典列表的文件读入python?
【发布时间】:2016-02-21 16:58:09
【问题描述】:

我创建了一个文件,其中包含我正在使用的字典列表。不幸的是,我不确定如何以相同的格式将该文件重新导入 python。

我最初将文件写成 JSON 和文本,如下所示:

d = list_of_dics
jsonarray = json.dumps(d)

with open('list_of_dics.txt', 'w') as outfile:
    json.dump(jsonarray, outfile)

with open('list_of_dics.json', 'w') as outfile:
    json.dump(jsonarray, outfile)

谁能建议一种将这些以相同格式(即字典列表)重新导入 python 的方法?

【问题讨论】:

  • 这里只是一个猜测,但通常如果库为 json 函数提供“编码”(在这种情况下为.dump),它也会提供来自 json 函数的“解码”。你检查过文档吗?

标签: python dictionary


【解决方案1】:

您错误地使用了json.dump()。您应该直接将d 传递给它,而不是json.dumps(d) 的输出。完成此操作后,您可以使用json.load() 检索您的数据。

with open('list_of_dics.txt', 'r') as infile:
    d = json.load(infile)

【讨论】:

  • 啊,明白了——这就是为什么我得到一个奇怪的输出。不过要澄清一下——使用json.load(infile)给了我一个unicode字符串。有什么方法可以直接将其加载为 dics 列表?
  • 没关系,明白了 - 只需从列表的开头和结尾删除 " 即可取消格式化。使用上面的方法就完美了。
【解决方案2】:

json.dumps(d)

您已经在一个字符串中(JSON-)编码列表 d(您将其分配给一个误导性地称为 jsonarray 的变量)。

json.dump(jsonarray, outfile)

您已对该 字符串 进行 JSON 编码并将结果写入 outfile

所以它现在(不必要地)在文件 list_of_dics.txtlist_of_dics.json 中双重 JSON 编码。

干净地从那里取回它(不诉诸manual string manipulation),您必须对其进行两次解码:

import json

with open('list_of_dics.json', 'r') as infile:
    recovered_d = json.loads(json.load(infile))

【讨论】:

    猜你喜欢
    • 2022-08-18
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多