Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading