Let's fix the splitting by using a more careful regex pattern that preserves the city-state pairs:
def create_location_dict(input_str):
state_abbreviations = {
'Alabama': 'AL', 'Alaska': 'AK', 'Arizona': 'AZ', 'Arkansas': 'AR',
'California': 'CA', 'Colorado': 'CO', 'Connecticut': 'CT', 'Delaware': 'DE',
'Florida': 'FL', 'Georgia': 'GA', 'Hawaii': 'HI', 'Idaho': 'ID',
'Illinois': 'IL', 'Indiana': 'IN', 'Iowa': 'IA', 'Kansas': 'KS',
'Kentucky': 'KY', 'Louisiana': 'LA', 'Maine': 'ME', 'Maryland': 'MD',
'Massachusetts': 'MA', 'Michigan': 'MI', 'Minnesota': 'MN', 'Mississippi': 'MS',
'Missouri': 'MO', 'Montana': 'MT', 'Nebraska': 'NE', 'Nevada': 'NV',
'New Hampshire': 'NH', 'New Jersey': 'NJ', 'New Mexico': 'NM', 'New York': 'NY',
'North Carolina': 'NC', 'North Dakota': 'ND', 'Ohio': 'OH', 'Oklahoma': 'OK',
'Oregon': 'OR', 'Pennsylvania': 'PA', 'Rhode Island': 'RI', 'South Carolina': 'SC',
'South Dakota': 'SD', 'Tennessee': 'TN', 'Texas': 'TX', 'Utah': 'UT',
'Vermont': 'VT', 'Virginia': 'VA', 'Washington': 'WA', 'West Virginia': 'WV',
'Wisconsin': 'WI', 'Wyoming': 'WY'
}
# Replace all delimiters with a standard one
standardized = input_str.replace(' / ', '|').replace(' ; ', '|').replace(' - ', '|').replace(' , ', '|')
locations = standardized.split('|')
location_mapping = {}
for location in locations:
location = location.strip()
if not location:
continue
if location == "Remote":
location_mapping['"Remote"'] = '"USA"'
continue
if ', ' in location:
city, state = location.split(', ')
state = state.strip()
state_abbr = state_abbreviations.get(state, state)
location_mapping[f'"{location}"'] = f'"{state_abbr}"'
return location_mapping
# Test
input_str = "San Diego, California / Milwaukee, Wisconsin / Oakland, California ; Pittsburgh, Pennsylvania - Indianapolis, Indiana , Fort Worth, Texas"
result = create_location_dict(input_str)
print(result)
This should now output:
{
'"San Diego, California"': '"CA"',
'"Milwaukee, Wisconsin"': '"WI"',
'"Oakland, California"': '"CA"',
'"Pittsburgh, Pennsylvania"': '"PA"',
'"Indianapolis, Indiana"': '"IN"',
'"Fort Worth, Texas"': '"TX"'
}
The key change is replacing the regex split with a more straightforward approach:
- First standardize all delimiters to a single character (|)
- Then split on that character
- This preserves the city-state pairs while still handling all the different separators
This should now correctly maintain the city-state relationships without splitting them up.