I'd like to know if I can turn an txt file in a list, and inside the list, a dict, just like the example
people = [{'name': 'Jhon', 'age':18}, {'name': 'Ian', 'age':20}, {'name': 'Annie', 'age':14}]
EDIT
The txt file looks like this:
Jhon, 18
Ian, 20
Annie, 14
people = []
with open("./data.txt") as f:
for line in f:
name, age = line.split()
people.append({"name": name, "age": int(age)})
or another way of doing it:
with open("./data.txt") as f:
people = [
{"name": name, "age": int(age)} for line in f for name, age in [line.split()]
]
output:
[{'name': 'Jhon,', 'age': 18},
{'name': 'Ian,', 'age': 20},
{'name': 'Annie,', 'age': 14}]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.