Python:将文本文件(每一行都是字典结构)读取到字典中

标签 python file dictionary

我正在尝试将文件读取到字典中,每一行都已经采用字典格式:

输入.txt:

{u'FirstName': u'John', u'Title': u'Mr', u'LastName': u'Doe'}
{u'FirstName': u'Mary', u'Title': u'Ms', u'LastName': u'Doe'}

然后我尝试执行以下操作:

with open("input.txt", "r") as ins:
    for line in ins:
        data = {}
        data = line
        print(data["Title"])

我遇到了错误:

    <ipython-input-18-a5a5994a6c1d> in main()
         18             data = {}
         19             data = line
    ---> 20             print(data["Title"])
         21 
         22 

TypeError: string indices must be integers, not str
<小时/>

我错过了什么以及将 input.txt 的每一行读取到字典中的正确方法是什么?谢谢!

最佳答案

您可以使用 ast 中的方法 literal_eval图书馆,这样:

import ast
with open("input.txt", "r") as ins:
    for line in ins:
        data = ast.literal_eval(line)
        print(data["Title"])
        print type(data) #To Check data type

现在,在你的原始代码上:

with open("input.txt", "r") as ins:
    for line in ins:
        data = {} #You are creating a new dictionary every iteration of for loop
        data = line #Re-defining data, which becomes string
        print(data["Title"]) #Then here you try index the data (string) with  a string ...that's wrong, string indexes are intergers 

关于Python:将文本文件(每一行都是字典结构)读取到字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34051412/

相关文章:

javascript - 在 IE9 中将用户指定的文件作为字符串读取

dictionary - 是 "bad form"在一条语句中进行map lookup和type assertion吗?

python - json对象解码错误

python - 如何从 .csv 文件加载数据而不导入 .csv 模块/库

c++ - 使用多线程将标准输出重定向到文件

ios - 在for循环后按值对字典数组进行排序?

python pandas 非唯一字典键

python - python中的矩阵镜像

Python 类型错误 : 'str' object is not callable when calling type function

javascript - 使用 Node js 触发 Jenkins 构建