How to read a list of dicts from a txt file?

I would like to read this txt file and get a list of dictionaries in python:

data.txt:

[{"name": "Aaron", "age": "1"}, {"name": "Bruce", "age": "2"}]

Whereas:

with open('data.txt','r') as f:
    list_of_dict = f.read()
print(list_of_dict[0])

Prints –> {"name": "Aaron", "age": "1"}

print(list_of_dict[1])

Prints –> {"name": "Bruce", "age": "2"}

print(type(list_of_dict[1])

Prints –> dict

print(type(list_of_dict)

Prints –> list

Thank you

>Solution :

Use json.load(file) instead of file.read()

import json
with open("a.txt", encoding="UTF8") as f:
    a = json.load(f)

print(type(a)) # <class 'list'>
print(a[0])
print(a[1])

document: https://docs.python.org/3/library/json.html

Leave a Reply