DEV Community

Discussion on: Solving the Problem Sets of CS50's Introduction to Programming with Python — One at a Time: Problem Set 6

Collapse
 
aristhera profile image
Gebhard • Edited

Edit: This relates to scourgify.py
Hi there,
since I didn't fully understand the csv-methods from the lesson I used a different approach (because we need split() and split creates a list and I'm afraid I understand lists better than DictWriter ;-(: in the open('before.csv') part I created a clean list, 'clean' meaning looking like this: ['Hannah', 'Abbott', 'Hufflepuff', 'Katie', 'Bell', 'Gryffindor', ...] using the methods we need anyway - lstrip, rstrip etc. Now in opening/writing 'after.csv' we have a list where every third item is first name, last name, house which we address with indices like i*3, i*3+1, i*3+2 (with i being the variable in the for-loop) and write it in after.csv with .writerow

Collapse
 
rivea0 profile image
Eda

Hi, that's a great idea for a solution without csv methods! The csv module actually makes the job easier and the code more readable, though.
Using DictWriter is easy, after you open the file, you just create a "writer" object and write its header field names such as:

writer = csv.DictWriter(csvfile, fieldnames=['first', 'last', 'house'])
writer.writeheader()
Enter fullscreen mode Exit fullscreen mode

Reading the "before" file is also easy, after opening it, you create a "reader" object this time, and can read each row with a loop. For example, splitting the names might look like this:

reader = csv.DictReader(before)
for row in reader:
    last_name, first_name = row['name'].split(',')
Enter fullscreen mode Exit fullscreen mode

Then, the writerow() method can be used for the writer object, passing a dictionary using the field names as keys.

One of the beautiful things in programming is that actually there are many ways for a solution, and elegance is mostly a matter of opinion. Thanks for sharing a different perspective.
And, thanks for an article idea, maybe I do a write-up some day on some basic csv methods :)

Collapse
 
aristhera profile image
Gebhard

Cool, do that.
Matter of fact I used the writer-object for writing headers just like you.
writerow() I used like:

`for i in range(len(liste)//3):
      writer.writerow({'first': liste[i*3], etc. .....})`
Enter fullscreen mode Exit fullscreen mode

and the main difference is in handling the 'before'-part. I just created the list, no reader = csv.DictReader(before)
But many roads lead to Rome and I'd love to read your piece on csv methods