I am trying to connect google's geocode api and github api to parse user's location and create a list out of it.
The array (list) I want to create is like this:
location, lat, lon, count
San Francisco, x, y, 4
Mumbai, x1, y1, 5
Where location, lat and lon is parsed from Google geocode, count is the occurrence of that location. Eevery time a new location is added: if it exists in the list the count is incremented otherwise it is appended to the array(list) with location, lat, lon and the count should be 1.
Another example:
location, lat, lon, count
Miami x2, y2, 1 #first occurrence
San Francisco, x, y, 4 #occurred 4 times already
Mumbai, x1, y1, 5 #occurred 5 times already
Cairo, x3, y3, 1 #first occurrence
I can already get the user's location from github and can get the geocoded data from google. I just need to create this array in python which I'm struggling with.
Can anyone help me? thanks.
This is sort of an amalgamation of all the other recommended ideas:
This uses defaultdict, which, as you can see allows for an easy way to both:
RETURNS:
This answer makes an (unverified) assumption that the granularity of your lat/lon pairs are unlikely to repeat, but that in fact you're only interested in making counts-by-city.
This would be better stored as a dictionary, indexed by city name. You could store it as two dictionaries, one dictionary of tuples for latitude/longitude (since lat/long never changes):
And a
collections.defaultdict
for the count, so that it always starts at 0:Python has a pre-baked class specifically for counting occurences of things: its called
collections.Counter
. If you can generate an iterator that gives successive tuples(city, lat, lon)
from your input data (perhaps with a generator expression), simply passing that intoCounter
will directly give you what you're looking for. eg,If you need to be able to add more locations as the program runs instead of batching them, put the relevant tuples into that Counter's
update
method.How about using a python dict? You can read about them here
http://docs.python.org/2/tutorial/datastructures.html#dictionaries
Here is a sample implementation:
With
collections.Counter
, you could do :