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


Messages In This Thread
get state code, state name and state abbreviation - by Larz60+ - Oct-11-2017, 01:38 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
Brick 3 features for python flask state. aaronxiongli 0 2,785 Nov-09-2020, 03:19 AM
Last Post: aaronxiongli
Lightbulb I built a state monitor using Python+Flask! (for new user) aaronxiongli 0 1,808 Nov-04-2020, 08:11 AM
Last Post: aaronxiongli
  JSON file with links for each US state Open Data Page Larz60+ 5 5,932 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