Python Forum
get state code, state name and state abbreviation
Thread Rating:
  • 1 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
get state code, state name and state abbreviation
#1
The following code will create a json file containing data for US states and possessions,
and presents a method for retrieving any missing two fields based on the field that is known.
The main function has examples for each of these conditions.

The state code is the FIPS state code which is used in most all datasets provided to the public by
the US government.

code:
import os
import json

class CreateStateCdJsonFile:
    def __init__(self):
        """
        Initialization includes state dictionary definition
        """
        datapath = f'{os.path.abspath(os.getcwd())}\\data'
        if not os.path.exists(datapath):
            os.makedirs(datapath)

        self.bynamefile = f'{datapath}/StateByName.json'
        self.bynamefile = os.path.abspath(self.bynamefile)

        self.byname = {
            'Alabama': {
                'state_cd': '01',
                'state_abbr': 'AL'
            },
            'Alaska': {
                'state_cd': '02',
                'state_abbr': 'AK'
            },
            'Arizona': {
                'state_cd': '04',
                'state_abbr': 'AZ'
            },
            'Arkansas': {
                'state_cd': '05',
                'state_abbr': 'AR'
            },
            'California': {
                'state_cd': '06',
                'state_abbr': 'CA'
            },
            'Colorado': {
                'state_cd': '08',
                'state_abbr': 'CO'
            },
            'Connecticut': {
                'state_cd': '09',
                'state_abbr': 'CT'
            },
            'Delaware': {
                'state_cd': '10',
                'state_abbr': 'DE'
            },
            'District of Columbia': {
                'state_cd': '11',
                'state_abbr': 'DC'
            },
            'Florida': {
                'state_cd': '12',
                'state_abbr': 'FL'
            },
            'Georgia': {
                'state_cd': '13',
                'state_abbr': 'GA'
            },
            'Hawaii': {
                'state_cd': '15',
                'state_abbr': 'HI'
            },
            'Idaho': {
                'state_cd': '16',
                'state_abbr': 'ID'
            },
            'Illinois': {
                'state_cd': '17',
                'state_abbr': 'IL'
            },
            'Indiana': {
                'state_cd': '18',
                'state_abbr': 'IN'
            },
            'Iowa': {
                'state_cd': '19',
                'state_abbr': 'IA'
            },
            'Kansas': {
                'state_cd': '20',
                'state_abbr': 'KS'
            },
            'Kentucky': {
                'state_cd': '21',
                'state_abbr': 'KY'
            },
            'Louisiana': {
                'state_cd': '22',
                'state_abbr': 'LA'
            },
            'Maine': {
                'state_cd': '23',
                'state_abbr': 'ME'
            },
            'Maryland': {
                'state_cd': '24',
                'state_abbr': 'MD'
            },
            'Massachusetts': {
                'state_cd': '25',
                'state_abbr': 'MA'
            },
            'Michigan': {
                'state_cd': '26',
                'state_abbr': 'MI'
            },
            'Minnesota': {
                'state_cd': '27',
                'state_abbr': 'MN'
            },
            'Mississippi': {
                'state_cd': '28',
                'state_abbr': 'MS'
            },
            'Missouri': {
                'state_cd': '29',
                'state_abbr': 'MO'
            },
            'Montana': {
                'state_cd': '30',
                'state_abbr': 'MT'
            },
            'Nebraska': {
                'state_cd': '31',
                'state_abbr': 'NE'
            },
            'Nevada': {
                'state_cd': '32',
                'state_abbr': 'NV'
            },
            'New Hampshire': {
                'state_cd': '33',
                'state_abbr': 'NH'
            },
            'New Jersey': {
                'state_cd': '34',
                'state_abbr': 'NJ'
            },
            'New Mexico': {
                'state_cd': '35',
                'state_abbr': 'NM'
            },
            'New York': {
                'state_cd': '36',
                'state_abbr': 'NY'
            },
            'North Carolina': {
                'state_cd': '37',
                'state_abbr': 'NC'
            },
            'North Dakota': {
                'state_cd': '38',
                'state_abbr': 'ND'
            },
            'Ohio': {
                'state_cd': '39',
                'state_abbr': 'OH'
            },
            'Oklahoma': {
                'state_cd': '40',
                'state_abbr': 'OK'
            },
            'Oregon': {
                'state_cd': '41',
                'state_abbr': 'OR'
            },
            'Pennsylvania': {
                'state_cd': '42',
                'state_abbr': 'PA'
            },
            'Rhode Island': {
                'state_cd': '44',
                'state_abbr': 'RI'
            },
            'South Carolina': {
                'state_cd': '45',
                'state_abbr': 'SC'
            },
            'South Dakota': {
                'state_cd': '46',
                'state_abbr': 'SD'
            },
            'Tennessee': {
                'state_cd': '47',
                'state_abbr': 'TN'
            },
            'Texas': {
                'state_cd': '48',
                'state_abbr': 'TX'
            },
            'Utah': {
                'state_cd': '49',
                'state_abbr': 'UT'
            },
            'Vermont': {
                'state_cd': '50',
                'state_abbr': 'VT'
            },
            'Virginia': {
                'state_cd': '51',
                'state_abbr': 'VA'
            },
            'Washington': {
                'state_cd': '53',
                'state_abbr': 'WA'
            },
            'West Virginia': {
                'state_cd': '54',
                'state_abbr': 'WV'
            },
            'Wisconsin': {
                'state_cd': '55',
                'state_abbr': 'WI'
            },
            'Wyoming': {
                'state_cd': '56',
                'state_abbr': 'WY'
            },
            'American Samoa': {
                'state_cd': '60',
                'state_abbr': 'AS'
            },
            'Federated States of Micronesia': {
                'state_cd': '64',
                'state_abbr': 'FM     '
            },
            'Guam     ': {
                'state_cd': '66',
                'state_abbr': 'GU'
            },
            'Marshall Islands': {
                'state_cd': '68',
                'state_abbr': 'MH'
            },
            'Commonwealth of the Northern Mariana Islands': {
                'state_cd': '69',
                'state_abbr': 'MP'
            },
            'Palau': {
                'state_cd': '70',
                'state_abbr': 'PW'
            },
            'Puerto Rico': {
                'state_cd': '72',
                'state_abbr': 'PR'
            },
            'U.S. Minor Outlying Islands': {
                'state_cd': '74',
                'state_abbr': 'UM'
            },
            'U.S. Virgin Islands': {
                'state_cd': '78',
                'state_abbr': 'VI'
            }
        }
        self.bystatecd = {}
        self.byabbr = {}
        self.state_codes = {}
        self.expand_dict()

    def expand_dict(self):
        """
        takes the dictionary self.byname, creates tow more dictionaries with
        keys for state_code and state abbreviation and merge with self.byname
        to create dictionary self.state_codes which can be queried by state code,
        state name or state abbreviation and extract the remaining state information

        :return: None
        """
        # create by state code
        for key, value in self.byname.items():
            self.bystatecd[value['state_cd']] = {}
            self.bystatecd[value['state_cd']]['state_name'] = key
            self.bystatecd[value['state_cd']]['state_abbr'] = value['state_abbr']
        # create by state abbr
        for key, value in self.byname.items():
            self.byabbr[value['state_abbr']] = {}
            self.byabbr[value['state_abbr']]['state_name'] = key
            self.byabbr[value['state_abbr']]['state_cd'] = value['state_cd']
        self.state_codes['by_name'] = self.byname
        self.state_codes['by_state_cd'] = self.bystatecd
        self.state_codes['by_abbr'] = self.byabbr

    def create_json(self):
        """
        Ceates a json file in data directory.
        will create directory if not present.
        :return: None
        """
        with open(self.bynamefile, 'w') as jo:
            json.dump(self.state_codes, jo)

    def get_state_info(self, key):
        """
        gets state name, state code, state abbreviation by submitting any one
        of the three values.

        :param key: key one of (state name, state code, or state abbreviation)
        :return: statename, statecd, stateabbr
        """
        try:
            length = len(key)
            if length > 2:
                statename = key
                statecd = self.state_codes['by_name'][key]['state_cd']
                stateabbr = self.state_codes['by_name'][key]['state_abbr']
            elif key.isdigit():
                statename = self.state_codes['by_state_cd'][key]['state_name']
                statecd = key
                stateabbr = self.state_codes['by_state_cd'][key]['state_abbr']
            else:
                statename = self.state_codes['by_abbr'][key]['state_name']
                statecd = self.state_codes['by_abbr'][key]['state_cd']
                stateabbr = key
            return statename, statecd, stateabbr
        except:
            return None, None, None

    def print_results(self, stname, stcode, stabbr):
        """
        print results of a get_state_info call
        :param stname: state name
        :param stcode: state code
        :param stabbr: state abbreviation
        :return: None
        """
        print(f'state code: {stcode}')
        print(f'state name: {stname}')
        print(f'state abbr: {stabbr}')

    def show_state_info(self, key):
        """
        gets state name, state code, state abbreviation by submitting any one
        of the three values, and displays results.
        :param key: key one of (state name, state code, or state abbreviation)
        :return: None
        """
        stcode, stname, stabbr = self.get_state_info(key)
        self.print_results(stcode, stname, stabbr)

def main():
    """
    Test routine for CreateStateCdJsonFile class
    :return: None
    """
    cs = CreateStateCdJsonFile()
    cs.create_json()

    # Test routine
    with open(cs.bynamefile) as f:
        mystates = json.load(f)

    print('Access by state code')
    stcode, stname, stabbr = cs.get_state_info('08')
    cs.print_results(stcode, stname, stabbr)

    print('\nAccess by state_abbr')
    stcode, stname, stabbr = cs.get_state_info('MA')
    cs.print_results(stcode, stname, stabbr)

    print('\nAccess by state name')
    stcode, stname, stabbr = cs.get_state_info('Texas')
    cs.print_results(stcode, stname, stabbr)


if __name__ == '__main__':
    main()
The results from examples:
Output:
Access by state code state code: 08 state name: Colorado state abbr: CO Access by state_abbr state code: 25 state name: Massachusetts state abbr: MA Access by state name state code: 48 state name: Texas state abbr: TX
Reply
#2
There appears to be such in pypi already
https://pypi.python.org/pypi/us
Recommended Tutorials:
Reply
#3
It was fun writing it
Reply
#4
import pathlib
pathlib.Path.cwd() / 'data'
Output on Ubutu Linux:
Output:
PosixPath('/home/andre/data')
Same output on Windows:
Output:
WindowsPath('C:/Users/admin/AppData/Local/Programs/Python/Python36/data')
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
DeaD_EyE thanks, I'll use this.
I didn't even know this had been built into python (since 3.4) until you mentioned it.
It's worth exploring what's there, here's a sample that just touches the surface
(I could have made this look exactly like Linux ls, but I'm too tired to do so now).
from pathlib import Path


class SetPath:
    def __init__(self):
        self.make_paths()

    def make_paths(self):
        self.homepath = Path('.')
        self.show_contents(self.homepath)
        self.datapath = self.homepath / 'data'
        self.show_contents(self.datapath)
        self.zippath = self.homepath / '../ZipcodeData'
        self.show_contents(self.zippath)
        self.addrpath = self.zippath / 'ADDR'
        # print([f'{x}\n' for x in addrpath.iterdir()])
        self.show_contents(self.addrpath)


    @staticmethod
    def show_contents(folder):
        print(f'\ndir {folder.name}')
        for item in folder.iterdir():
            if item.is_dir():
                print(f'    d..{item}')
            else:
                print(f'    ...{item}')


if __name__ == '__main__':
    SetPath()
gives:
Output:
directory Name:     ...CreateStateCdJsonFile.py     d..data     ...FetchTiger2016AddrFiles.py     ...MakeCensusNameJson.py     ...SetPath.py     ...snippet.py     ...__init__.py directory Name: data     ...data\addrfiles.txt     ...data\StateByName.json directory Name: ZipcodeData     .....\ZipcodeData\4c90ea7b-1c0b-4ace-9eb0-a9eb01602f18.json     d....\ZipcodeData\ADDR     d....\ZipcodeData\ByState     .....\ZipcodeData\ea323919-fe1e-41e8-a53d-7404e0801116.json     .....\ZipcodeData\free-zipcode-database-Primary.csv     .....\ZipcodeData\free-zipcode-database.csv     .....\ZipcodeData\tlgdb_2017_a_us_addr.gdb.zip     d....\ZipcodeData\zcat directory Name: ADDR     d....\ZipcodeData\ADDR\AK_02     d....\ZipcodeData\ADDR\AL_01     d....\ZipcodeData\ADDR\AR_05     d....\ZipcodeData\ADDR\AS_03     d....\ZipcodeData\ADDR\AS_60     d....\ZipcodeData\ADDR\AZ_04     d....\ZipcodeData\ADDR\CA_06     d....\ZipcodeData\ADDR\CO_08     d....\ZipcodeData\ADDR\CT_09     d....\ZipcodeData\ADDR\CZ_07     d....\ZipcodeData\ADDR\DC_11     d....\ZipcodeData\ADDR\DE_10     .....\ZipcodeData\ADDR\dirs.txt     d....\ZipcodeData\ADDR\FL_12     d....\ZipcodeData\ADDR\FM_64     d....\ZipcodeData\ADDR\GA_13     .....\ZipcodeData\ADDR\GetAllAddr.bat     .....\ZipcodeData\ADDR\makeDir.bat     .....\ZipcodeData\ADDR\tl_2016_01001_addr.zip     d....\ZipcodeData\ADDR\TN_47     d....\ZipcodeData\ADDR\TX_48     d....\ZipcodeData\ADDR\UM_74     d....\ZipcodeData\ADDR\UT_49     d....\ZipcodeData\ADDR\VA_51     d....\ZipcodeData\ADDR\VI_52     d....\ZipcodeData\ADDR\VI_78     d....\ZipcodeData\ADDR\VT_50     d....\ZipcodeData\ADDR\WA_53     d....\ZipcodeData\ADDR\WI_55     d....\ZipcodeData\ADDR\WV_54     d....\ZipcodeData\ADDR\WY_56
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Brick 3 features for python flask state. aaronxiongli 0 2,647 Nov-09-2020, 03:19 AM
Last Post: aaronxiongli
Lightbulb I built a state monitor using Python+Flask! (for new user) aaronxiongli 0 1,711 Nov-04-2020, 08:11 AM
Last Post: aaronxiongli
  JSON file with links for each US state Open Data Page Larz60+ 5 5,668 Mar-05-2017, 11:19 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020