Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Counter results to csv file

this question is based on my pervious question: Python list help (incrementing count, appending)

I am able to create the following output when I do print c;

Counter({(u'New Zealand', 174.885971, -40.900557): 1, (u'Ohio, USA', -82.90712300000001, 40.4172871): 1})

Which is exactly how I want and now I would like to know how I can write this to a csv file. Each row will represent a new location, lon/lat, count.

I want to loop through the counter and access these parts: writer.writerow(["A", "B", "C"]);

A is the location like New Zealand, B is the lat/lon, C is the count of appearance,

How can I access count's results and get those desired parts? Thanks.

like image 688
chatu Avatar asked Apr 23 '13 15:04

chatu


1 Answers

A Counter is a subclass of the standard dict class; you can loop over the items in the dictionary with .iteritems() (python 2) or just .items() (python 3):

for key, count in your_counter.iteritems():
    location, lat, long = key
    writer.writerow([location, lat, long, count])

This writes four columns, with 2 separate columns for the latitude and longitude. If you want to combine those into one column, say, as a string with a slash between the two coordinates, just use string formatting:

for key, count in your_counter.iteritems():
    location, lat, long = key
    writer.writerow([location, '{}/{}'.format(lat, long), count])
like image 165
Martijn Pieters Avatar answered Sep 22 '22 10:09

Martijn Pieters