Wednesday, August 30, 2006

Easy Pieces in Python: A Lookup Table

Often you find yourself with data that would be more useful in another form. For example, you might have a list of zip codes that you want to plot with Google Maps. Unfortunately, the Google Maps API only takes latitude and longitude. There is an online table of zip codes with cities, states, latitudes and longitudes at the US Census Bureau website, however. With a little bit of Python it is easy to convert your zip codes to latitude and longitude.

A line in the online data table looks like this:


If we split each line apart at the commas, we will end up with eight fields. Since Python counts from zero, this means the zip code is field number 1. The longitude and latitude are fields 4 and 5 respectively. Our script reads in the data file a line at a time, then creates a dictionary so we can look up each zip code and get a string representing the latitude and longitude. (For Google Maps, we want latitude first, and longitude expressed as a negative number.)

datafile = open('zips.txt', 'r')
lookup = {}
for line in datafile.readlines():
    items = line.split(',')
    zip = items[1]
    lat = items[5]
    lon = items[4]
    lookup[zip[1:-1]] = "%s, -%s" % (lat, lon)

We now can look up individual zip codes:

print lookup['91436']


'34.15098, -118.488238'

Or we can transform all of our data at once:

ziplist = ['02139', '02141', '02142', ...]
print [lookup[z] for z in ziplist]


['42.364688, -71.104155', '42.370701, -71.088277', '42.362025, -71.083011', ...]

Tags: | | | |