Home > Software design >  How to read a list of dicts from a txt file?
How to read a list of dicts from a txt file?

Time:06-23

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

CodePudding user response:

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

CodePudding user response:

Try using json module:

import json

with open("data.txt", "r") as f_in:
    list_of_dict = json.load(f_in)

print(list_of_dict[0])
print(list_of_dict[1])
print(type(list_of_dict[1]))
print(type(list_of_dict))

Prints:

{'name': 'Aaron', 'age': '1'}
{'name': 'Bruce', 'age': '2'}
<class 'dict'>
<class 'list'>
  • Related