Write a function named \"loadStateDict(filename) that takes a filename and retur
ID: 3904330 • Letter: W
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 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.
Sample code:
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)
Explanation / Answer
def loadStateDict(filename): d = {} with open(filename, 'r') as f: for line in f: words = line.strip().split(',') if len(words[1]) != 0: d[words[1]] = words[0] return d filename = input('Enter state code file name: ') stateDic = loadStateDict(filename) print(stateDic)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.