Edamame
Edamame

Reputation: 25366

Python: read a text file (each line is of dictionary structure) to a dictionary

I am trying to read a file to dictionary, each line is already in a dictionary format:

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'}

I then tried to do the following:

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

Bit I got error:

    <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

What did I miss and what's the proper way to read each line of input.txt to a dictionary? Thanks!

Upvotes: 5

Views: 6065

Answers (4)

Iron Fist
Iron Fist

Reputation: 10951

You can use the method literal_eval from ast library, this way:

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

Now, on your original code:

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 

Upvotes: 5

kvorobiev
kvorobiev

Reputation: 5070

In your for-loop you read strings from file. And you need to convert it to Python dict. You could use ast.literal_eval to convert formatted str to dict.

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

Upvotes: 0

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

We can achieve the end result by 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"])

Upvotes: 2

John Gordon
John Gordon

Reputation: 33310

This piece of code:

data = line

undoes data's previous existence as a dictionary, and re-assigns it to be a string. Strings are indexed only by integers, hence the error message.

Upvotes: 1

Related Questions