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.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With