![]() |
get state code, state name and state abbreviation - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Code sharing (https://python-forum.io/forum-5.html) +--- Thread: get state code, state name and state abbreviation (/thread-5563.html) |
get state code, state name and state abbreviation - Larz60+ - Oct-11-2017 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:
RE: get state code, state name and state abbreviation - metulburr - Oct-11-2017 There appears to be such in pypi already https://pypi.python.org/pypi/us RE: get state code, state name and state abbreviation - Larz60+ - Oct-11-2017 It was fun writing it RE: get state code, state name and state abbreviation - DeaD_EyE - Oct-11-2017 import pathlib pathlib.Path.cwd() / 'data'Output on Ubutu Linux: Same output on Windows:
RE: get state code, state name and state abbreviation - Larz60+ - Oct-12-2017 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:
|