【问题标题】:How to turn an txt file to a list with dict如何使用 dict 将 txt 文件转换为列表
【发布时间】:2021-11-30 15:44:23
【问题描述】:

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

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

编辑

txt 文件如下所示:

Jhon, 18
Ian, 20
Annie, 14

【问题讨论】:

标签: python list dictionary txt


【解决方案1】:
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}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多