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

时间:2015-12-02 19:33:42

标签: python file dictionary

我正在尝试将文件读入字典,每行都已经是字典格式:

input.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读入字典的正确方法是什么?谢谢!

4 个答案:

答案 0 :(得分:1)

您可以使用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 

答案 1 :(得分:1)

我们可以通过ast.literal_eval获得最终结果。

from ast import literal_eval
with open("input.txt", "r") as ins:
    for line in ins:
        your_dict = literal_eval(line)
        print(your_dict["Title"])

答案 2 :(得分:0)

在for循环中,您可以从文件中读取字符串。您需要将其转换为Python dict。您可以使用ast.literal_eval将格式化的str转换为dict

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

答案 3 :(得分:0)

这段代码:

data = line

撤消data以前作为字典的存在,并将其重新指定为字符串。字符串仅由整数索引,因此出现错误消息。