Question

Write a function named "loadStateDict(filename) that takes a filename and returns a dictionary of 2-character state...

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)

 
0 0
Add a comment Improve this question Transcribed image text
Answer #1
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)
Add a comment
Know the answer?
Add Answer to:
Write a function named "loadStateDict(filename) that takes a filename and returns a dictionary of 2-character state...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT