【问题标题】:How to read a list of dicts from txt file [duplicate]如何从 txt 文件中读取字典列表 [重复]
【发布时间】:2019-01-13 04:22:37
【问题描述】:

我正在尝试从文本文件中获取存储在列表中的字典

我搜索了一个json函数,它可以将字符串分隔并保存在一个列表(字典列表)中,但不知道有没有这样的东西。

txt:

[{"Principal": ["Jhon","Anderson","40"]}, {"Secretary": ["Marie","Garcia","29"]},{"Councilor": ["Alan", "Smith","33"]}]

py 代码:

stringvar=textfile.read()

//for 或下面的函数

dictionaries=json.loads(textfile.read())
otherlist=dictionaries

【问题讨论】:

  • 我想我是具体的,txt文件看起来就像它在一行中,我想要实现的是将它保存在几个字典中,稍后我会放在一个列表中,谢谢跨度>
  • dictionaries=json.loads(textfile.read()) 已经是一个字典列表。你想念什么?

标签: python list dictionary text-files


【解决方案1】:

如果您希望在 Python 中从 txt 文件中加载字典列表,您可以使用 ast 模块中的 literal_eval 函数来执行此操作,以评估文件中字符串的表达式:

import ast

data = []
with open("data.txt", "r") as inFile:
    data = ast.literal_eval(inFile.read())

【讨论】:

  • json.loads 有什么问题?
  • @mkiever json.loads 应该是从文件加载字典的方式,正如 Francesco Boi 在下面的答案中所提出的那样。我只是提出了一个替代方案,认为 OP 无法使用问题中提到的json.load 达到预期的结果。
【解决方案2】:

首先,这些类型的文件称为 json 文件。

您可以打开并阅读它们:

import json
f = open("results/results.json")
data = json.load(f)

json 文件中的方括号定义一个数组,而 curl 括号一个对象。前者在python中会转化为列表,后者会转化为字典。

所以在您的情况下,data 将是一个字典列表。

可以通过字典类keys()values()的方法获取值和键,也可以同时获取items()

要完整,您的 json 元素应该具有相同的结构,只有字段应该改变。例如考虑一个元素:

{"role"    : "Principal",
 "name:    : "Jhon",
 "surname. : "Anderson",
 "age":   40}

通过这种方式,您可以更轻松地遍历您的 json

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 2020-06-01
    • 2012-11-30
    • 1970-01-01
    • 2016-08-04
    • 2021-05-09
    相关资源
    最近更新 更多