Home > Back-end >  Python: How to read a List of List containing dictionary from a text file to a list object
Python: How to read a List of List containing dictionary from a text file to a list object

Time:09-30

I have a text file. This a list of list which hold a dictionary. How do I achieve this?

[[
    {'amount': 23418.945947265624, 'ID': 'ID:153572', 'loan': None, 'status': 'SUCCESS'}, 
    {'amount': -106921.3234375, 'ID': 'ID:82295', 'loan': None,  'status': 'SUCCESS'}, 
    {'amount': 52857.603124999994, 'ID': 'ID:102957', 'loan': None, 'status': 'SUCCESS'}, 
    {'amount': 50788.3150390625, 'ID': 'ID:157364', 'loan': None,  'status': 'SUCCESS'}, 
    {'amount': -93917.1078125, 'ID': 'ID:96633', 'loan': None,  'status': 'SUCCESS'}
]]

I have tried the following:

with open('case1-gather_results.txt') as f:
    lines = f.readlines()
    
testString = lines[0]

json_acceptable_string = testString.replace("'", "\"")
print(json_acceptable_string)
d = json.loads(json_acceptable_string)

Read the files to a list and one doing that, I have tried to parse the below error:

JSONDecodeError: Expecting value: line 1 column 70 (char 69)

CodePudding user response:

Try ast.literal_eval() instead:

from ast import literal_eval

with open('case1-gather_results.txt') as f:
    d = literal_eval(f.read())
  • Related