Created
June 29, 2013 20:21
-
-
Save j2labs/5892515 to your computer and use it in GitHub Desktop.
Example of using Python's csv module with DictReader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import csv | |
import json | |
# Get graffiti_locations.csv from: | |
# https://nycopendata.socrata.com/Social-Services/Graffiti-Locations/2j99-6h29? | |
filename = 'graffiti_locations.csv' | |
def read_csv(): | |
csv_data = [] | |
f = open(filename, 'r') | |
csv_file = csv.DictReader(f) | |
for row in csv_file: | |
csv_data.append(row) | |
f.close() | |
return csv_data | |
csv_data = read_csv() | |
print 'First row of CSV' | |
print csv_data[0], '\n\n' | |
def group_by_field(csv_data, field_name='Status'): | |
grouped_data = {} | |
for row in csv_data: | |
status = row[field_name] | |
status_list = [] | |
if status in grouped_data: | |
status_list = grouped_data[status] | |
status_list.append(row) | |
grouped_data[status] = status_list | |
return grouped_data | |
grouped = group_by_field(csv_data) | |
print 'All statuses:', grouped.keys(), '\n\n' | |
print 'First closed location' | |
print grouped['Closed'][0], '\n\n' | |
print 'Total number of closed locations' | |
print len(grouped['Closed']), '\n\n' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment