Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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):

forkey, 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:

forkey, count in your_counter.iteritems():
    location, lat, long = key
    writer.writerow([location, '{}/{}'.format(lat, long), count])

Post a Comment for "Python Counter Results To Csv File"