Home > Mobile >  How to turn an txt file to a list with dict
How to turn an txt file to a list with dict

Time:10-12

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

CodePudding user response:

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}]
  • Related