Reputation: 29
Working on a typical Python project of quizzing a user on state's capitals. Instead of just copying and creating my own dictionary I'm reading a text file. I have the portion of the quiz set up(I think) and I'm struggling with creating the actual key-value pairs. The text file looks like this:
Alabama
Montgomery
Alaska
Juneau
Arizona
Phoenix
Arkansas
Little Rock etc....
I can't figure out how to read the first line as the key(state) and second line as the value(capital). Once I have the correct variables I will change what my main method calls. Any help or feedback is appreciated. Thanks!
Here is my code:
NUM_STATES = 5
def make_dictionary():
with open('state_capitals.txt', 'r') as f:
d = {}
for line in f:
d[line.strip()] = next(f, '').strip()
def main():
d = make_dictionary()
correct = 0
incorrect = 0
for count in range(NUM_STATES):
state, capital = d.popitem()
print('Enter a capital of ', state, '?', end = '')
response = input()
if response.lower() == capital.lower():
correct += 1
print('Correct!')
else:
incorrect += 1
print('Incorrect.')
print('The number of correct answers is: ', correct)
print('The number of incorrect answers is: ', incorrect)
main()
Upvotes: 0
Views: 148
Reputation: 336
I would suggest reading the file as a string then do this
with open('state_capitals.txt', 'r') as f:
file_ = f.read()
file_ = list(filter(lambda x:not x == "", file_.split("\n")))
keys = [key for index,key in enumerate(file_) if index%2 == 0]
values = [value for index,value in enumerate(file_) if not index%2 == 0]
dictionary = dict(zip(keys, values))
print(dictionary)
Upvotes: 0