From Sea to Shining Sea: us for Python


I am an extremely lazy person. I started on a new project recently that required me to delve into state and census tract data. The thought of the effort involved in locating and copy-and-pasting a dict mapping US state abbreviations to FIPS codes was so overwhelming that I just wanted to go take a nap instead. And once I got the FIPS code dict, I’d have to use it to generate URLs for state shapefile downloads. Ugh!

So instead of (yet again) copying a dict from some other source, I decided to do something more permanent. us, the result of my laziness, is a Python package that contains all sorts of state meta data in an easy to use API.

Looking up a FIPS code by state abbreviation is super easy:

>>> import us
>>> us.states.MD
>>> us.states.MD.fips

All of the states are available a nice alphabetically ordered list:

>>> us.STATES
[<State:Alabama>, <State:Alaska>, <State:Arizona>,...

And if you need US territories, you’ve got access to that too. You can get territories alone or all states and territories combined:

[<State:American Samoa>, <State:Guam>,...
[<State:Alabama>, <State:Alaska>, <State:American Samoa>,...

It’s also quite easy to generate your own mapping dict for any of the fields provided by the State class:

>>> fips_to_name = us.states.mapping('fips', 'name')
>>> fips_to_name['24']

If you need even more flexibility, you can use the lookup() method to find state objects by FIPS, abbreviation, or name.

>>> us.states.lookup('24')
>>> us.states.lookup('md')
>>> us.states.lookup('maryland')

Phonetic name matching is also supported. This can be useful in cases where you are taking input from a user that may not be up to snuff on his or her spelling.

>>> us.states.lookup('murlynd')

To get started, install with pip:

pip install us

There’s other great stuff in here too like easy access to shapefile URLs for various regions within each state, capitals, years of statehood, and a CLI for quick state data lookups from the command prompt. Any feedback on or contributions to the project would be greatly appreciated!