-1

I have a file containing dictionaries like this:

{'name': 'peter', 'age': '16', 'class': None}
{'name': 'john', 'age': '20', 'class': 'B'}
{'name': 'alex', 'age': '18', 'class': 'C'}

I am trying to read the contents from the file and convert the lines back into dictionaries.

with open(file.txt) as f:
    for line in f:
        if 'name' in line:
            d = json.loads(json.dumps(line.strip()))
            print(type(d))

But the type is still str? How can I get them to be dictionary object again?

vaultah
  • 44,105
  • 12
  • 114
  • 143
ChaChaPoly
  • 1,811
  • 5
  • 17
  • 39

1 Answers1

2

They're not JSON, but Python dictionary literals.

You can use ast.literal_eval to convert literals to python object.

import ast

with open('file.txt') as f:
    for line in f:
        if 'name' in line:
            d = ast.literal_eval(line)
            print(type(d))
falsetru
  • 357,413
  • 63
  • 732
  • 636