5

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.

1 Answer 1

8

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])
Sign up to request clarification or add additional context in comments.

5 Comments

How can I sort these ascending based on the count? @Martijn
I tried sorted(your_counter.iteritems()) but that sorts by location where I need it for count. Thanks.
Use for key, count in reversed(your_counter.most_common()): instead.
avoid long as variable name, since it is a reserved word ;) just in case
@ZloySmiertniy: long is not a reserved word. It is the name of a built-in type in Python 2, one you rarely need to use directly. The type is gone altogether in py3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.