Search code examples
pythonfile-iovalueerror

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


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

Solution

  • 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