如何用dict将一个txt文件变成一个列表

How to turn an txt file to a list with dict

我想知道我是否可以在列表中打开一个txt文件,在列表中,一个dict,就像例子一样

people = [{'name': 'Jhon', 'age':18}, {'name': 'Ian', 'age':20}, {'name': 'Annie', 'age':14}]

编辑

txt 文件如下所示:

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)})

或另一种方法:

with open("./data.txt") as f:
    people = [
        {"name": name, "age": int(age)} for line in f for name, age in [line.split()]
    ]

输出:

[{'name': 'Jhon,', 'age': 18},
 {'name': 'Ian,', 'age': 20},
 {'name': 'Annie,', 'age': 14}]