import csv
students = []
with open("stu1.csv") as file:
reader = csv.reader(file)
for name, home in reader:
students.append({"name": name}, {"home": home})
for student in sorted(students, key =lambda student:student["name"]):
print(f"{student['name']} is from {student['home']}")
stu1.csv contains below data
Harry, Number, Pivet Drive
Ron, The burrow
Draco, Malfoy manor
CodePudding user response:
You were very close. There were actually 2 errors.
- there were 3 columns (in the first row) and you are unpacking 2 values.
- the
append()
takes 1 dict, but you were passing 2 dicts.
with the error fixed, this works:
import csv
students = []
f = "C:\\test\\test_file.csv"
with open(f) as file:
reader = csv.reader(file)
for name, home in reader:
students.append({"name": name, "home": home})
for student in sorted(students, key =lambda student:student["name"]):
print(f"{student['name']} is from {student['home']}")
returns this:
Draco is from Malfoy manor
Harry is from Number
Ron is from The burrow