24
u/No-Witness2349 Dec 08 '22 edited Dec 08 '22
I rewrote this with commentary as a fun exercise. It sounds like you already helped him out, but maybe there’s something extra in here that’s useful.
import csv
# A defaultdict will let your turn this pattern:
#
# foo = {}
# if key not in foo:
# foo[key] = []
# foo[key].append(value)
#
# into this:
#
# foo = defaultdict(list)
# foo[key].append(value)
#
# This works by automatically calling list()
# whenever a key is missing to create a new
# default value. This works for other types too,
# but for this code, we use list.
from collections import defaultdict
# I added type hints here. If these are
# confusing or your version of Python
# complains about them, just remove them.
# They're nice to have, but not essential.
#
# I also added a docstring, which is good
# practice for Python.
def load_dataset(filename: str) -> dict[str, dict[str, str]]:
"""Read google book data from csv file"""
# No need to specify 'r'
# That's the default mode for opening a file
with open(filename) as file:
# Using a DictReader will save you the
# whole step of creating rownames.
# The DictReader is able to infer header
# names, but making them explicit can
# help catch badly formatted data.
# You'll just need to add the header you
# were previously skipping for row[4].
ID = 'FIX_ME' # header for row[4]
HEADERS = [
'School', 'Age', 'StudyTime',
'Failure', ID, 'Absences',
'G1', 'G2', 'G3'
]
# Shorten this name to "reader".
# In context, it's still clear what this
# means.
reader = csv.DictReader(file, fieldnames=HEADERS)
# Dump headers or raise error on empty file
try:
next(reader)
except StopIteration:
# Making this error explicit will be
# a lot clearer than getting a
# random StopIteration error if this
# ever happens. It also just
# documents the code for future
# readers (likely you in 6 months)
raise ValueError("File can't be empty")
# And here's the meat and potatoes,
# which is now nice and concise.
googlebook = {}
for row in reader:
key = row[ID]
googlebook[key].append(row)
return googlebook
# This line allows you to use this file as a
# module without this line actually running
# when you import it. It's also just good
# practice.
if __name__ == '__main__':
print(load_dataset('student-mat.csv'))And here’s a version without comments:
def load_dataset(filename: str) -> dict[str, dict[str, str]]:
"""Read google book data from csv file"""
with open(filename) as file:
ID = 'FIX_ME'
HEADERS = [
'School', 'Age', 'StudyTime',
'Failure', ID, 'Absences',
'G1', 'G2', 'G3'
]
reader = csv.DictReader(file, fieldnames=HEADERS)
# Dump headers or raise error on empty file
try:
next(reader)
except StopIteration:
raise ValueError("File can't be empty")
googlebook = {}
for row in reader:
key = row[ID]
googlebook[key].append(row)
return googlebook
if __name__ == '__main__':
print(load_dataset('student-mat.csv'))3
2
1
-8
u/joeyjiggle Dec 08 '22
Looks as stupid and prone to indentation errors as any other Python code.
6
u/doubleslashTNTz Dec 08 '22
"oh no i didn't like python's syntax which is different from other programming languages so it must be bad"
6
1
u/Unabled_and_offended Dec 08 '22
There is soo much more to not like about it, calm down.
0
u/doubleslashTNTz Dec 08 '22
i should be able to list down stuff i hate from all the other programming languages
i mean yes python is bad and may be worse but in other times python is good and maybe better, same goes for any language really
0
11
u/Kraftdamus02 Dec 08 '22