python - DictReader get a value when a column # and row # are known -
i given csv file looks this
id, name, age, city 1, andy, 25, ann arbor 2, bella, 40, los angeles 3, cathy, 13, eureka ... ...
if want city
of id
=3, eureka example. there way efficiently instead of iterating each row? php code executing python script each time value, , feel being inefficient loop through csv file every time.
iterate on file once , save data dictionary:
data = {} open('input.csv') fin: reader = csv.dictreader(fin) record in reader: data[record['id']] = {k:v k,v in record.items() if k <> 'id'}
then access required key in dictionary:
print data[3]['city'] # eureka
in case want persist data in key:value format can save json
file:
import json import csv j = {} open('input.csv') fin: reader = csv.dictreader(fin) record in reader: j[record['id']] = {k:v k,v in record.items() if k <> 'id'} open('output.json','w') fout: json.dump(j,fout)
Comments
Post a Comment