Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You have several errors in your code:</p> <ol> <li>Not ignoring the first line of your csv file which contains 'name' and 'date'.</li> <li>Using strings to store dates instead of the <code>date</code> type.</li> <li>Attempting to subtract one string from another.</li> <li>Modifying items in <code>datedict</code> without first checking that they exist.</li> <li>The slashes in 1/1/2003 are going to be treated as divide signs and the result will be 0.</li> </ol> <p>Here is what your code would look like with these errors fixed:</p> <pre><code>import csv from collections import defaultdict import datetime from datetime import date import math def weeks(filename, start_date): # The defaultdict class will create items when a key is accessed that does # not exist datedict = defaultdict(set) with open(filename, 'r') as csvfile: filereader = csv.reader(csvfile, 'excel') read_header = False for row in filereader: # Ignore the first row of the file if not read_header: read_header = True continue # Strip out any whitespace cells = [col.strip() for col in row] name = cells[0] date_str = cells[1] # Parse the date string into a date row_date = datetime.datetime.strptime(date_str, '%d/%m/%Y').date() # Calculate the difference between dates delta = start_date-row_date # Convert from days to weeks, you could use math.floor() here if # needed delta_weeks = int(math.ceil(delta.days / 7.0)) datedict[name].add(delta_weeks) return datedict date_dict = weeks('a.csv', start_date=date(year=2013, month=1, day=1)) for name, dates in date_dict.iteritems(): print name, list(dates) </code></pre> <p>This prints out:</p> <pre><code>bil [351, 254] sam [519, 182] Mali [179] </code></pre> <p>You should be able to figure out how to get it to print 'weeks'.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload