Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading