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!

Answers


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"])

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 

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.


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"])

Need Your Help

Ubuntu: reboot "Failed to talk to init daemon" after 15.04 -> 15.10 update

linux ubuntu

I had a fully patched 15.04 installation and did the do-release-update. It's a VM with a popular US hoster, I have root and have performed earlier similar upgrades on this machine with no problems....