python - How do I write a csv file from a dictionary with multiple values per key? -
i posted question part of question. need write csv file in gives me name of technician, date worked on tract, , number of tracts on date. found way needed data dictionary key being name of technician , value being date , count using cursor through arcmap find data, using code so:
desc = arcpy.describe(inlayer) fields = desc.fields field in fields: srow in cursor: tech = srow.getvalue("technician") moddate = srow.getvalue("modifieddate") formdate = moddate.strftime("%m-%d-%y") if tech == "elizabeth": escontract = escontract + 1 eslist = [] eslist.append(formdate) estech.update(eslist) date in estech.iteritems(): if tech in listedtech: listedtech[tech].append(date) else: listedtech[tech] = [date]
where estech counter dictionary defined earlier , listedtech empty dictionary defined earier well.
listedtech when printed appear like:
listedtech = {u'elizabeth': [('05-11-2015', 6), ('05-13-2015', 16), ('05-12-2015', 16)] , u'michael': [('05-11-2015', 3)]}
how take dictionary named listedtech , turn csv file?
update
i have made dictionary list of dictionary called nl. when print list of dictionaries, this:
nl = [{u'elizabeth': [('05-11-2015', 6), ('05-13-2015', 16), ('05-12-2015', 16)]} , {u'michael': [('05-11-2015', 3)]}]
however, having issues still getting csv. when did dictwriter, came out weird each technician had own column 1 row of associated values csv file looks
elizabeth | michael
('05-11-2015', 6), ('05-13-2015', 16), ('05-12-2015', 16) | ('05-11-2015', 3)
instead of how want in each value on different row. code used this:
with open(csvfilename, 'w') f: fieldnames = ['elizabeth', 'michael'] dict_writer = csv.dictwriter(f, fieldnames = fieldnames) dict_writer.writeheader() dict_writer.writerows(nl)
what doing wrong?
you can use csv.dictwriter
. docs:
import csv open('names.csv', 'w') csvfile: fieldnames = ['first_name', 'last_name'] writer = csv.dictwriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerow({'first_name': 'baked', 'last_name': 'beans'}) writer.writerow({'first_name': 'lovely', 'last_name': 'spam'}) writer.writerow({'first_name': 'wonderful', 'last_name': 'spam'})
Comments
Post a Comment