value error(line 7 for name, home) when using csv library in python CS50P file i/o

Question:

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
Asked By: user14951994

||

Answers:

You were very close. There were actually 2 errors.

  1. there were 3 columns (in the first row) and you are unpacking 2 values.
  2. 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
Answered By: D.L
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.