Question: Write a function named loadStateDict(filename) that takes a filename and returns a dictionary of 2-character state codes and state names. The file has four columns
Write a function named "loadStateDict(filename) that takes a filename and returns a dictionary of 2-character state codes and state names. The file has four columns and they are separated by commas. The first column is the state full name and the second column is the state code. You don't have to worry about column 3 & 4. You should eliminate any row that is without a state code. Save the two columns into a dictionary with key = state code and value = state name. Return a dictionary at the end of the function.
d = { "AL" : "Alabama", "AK": "Alaska", ... } Sample code:
filename = input('Enter state code file name: ') stateDic = loadStateDict(filename )
I have this so far but I it results in the error below.
def loadStateDict(filename): d = {} import csv with open(filename, 'rt') as file: reader=csv.reader(file) for line in reader: states = line.strip().split(',') if len(states[1]) != 0: d.update({states[1]:states[0]})
return filename = input('Enter state code file name: ') stateDic = loadStateDict(filename ) print(stateDic)
Dict for line in reader: File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 56: ordinal not in range(128)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
