Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way of exchanging between lists?

Tags:

python

list

I want to have a list of cities and a list of postal codes, with the positions corresponding (if NYC is first in the city list, NYS's code will be first in the code list). Say I wanted to set x to NYC's zip code. I know it's possible to do this:

y = citylist.index('New York')
x = postcodelist[y]
xstring = str(x)

But, is there a way to equate the lists and do this in one line, such as:

x = postcodelist.citylist.index('New York').string
like image 277
tkbx Avatar asked Jun 08 '26 10:06

tkbx


2 Answers

If I understand correctly you have two parallel lists that you want to treat as essentially a list of keys and a list of values. If so, you can do something like the following:

>>> places = ['New York', 'Texas', 'California']
>>> zips = ['01010', '70707', '90909']
>>> place_zip_map = dict(zip(places, zips))
>>> place_zip_map['New York']
'01010'

Basically, take your list of places as your keys and your list of zips/postal codes as your values, use zip to combine them into a sequence of key-value pairs, and then use dict to create the dict that maps them to one another.

EDIT: And if you want to create a dictionary the other way to map postal codes/zips to the place you could use the same process, just flip the order of the lists in your zip. You could then combine the two resulting dicts into one if you wanted one structure that could look up either. As long as there's no place with the same name as a postal code, there should be no collisions.

like image 59
Daniel DiPaolo Avatar answered Jun 10 '26 22:06

Daniel DiPaolo


You could use pyzipcode:

>>> from pyzipcode import ZipCodeDatabase
>>> zcdb = ZipCodeDatabase()
>>> zcdb['10001'].city
u'New York'
>>> len(zcdb.find_zip(city="New York"))
167
>>> zcdb.find_zip(city="New York")[0].zip
u'10001'
>>> zcdb.find_zip(city="New York")[1].zip
u'10002'
>>> zcdb.find_zip(city="New York")[2].zip
u'10003'
like image 39
jterrace Avatar answered Jun 10 '26 23:06

jterrace