i have a question that might end up being a fairly simple fix but i am having a lot of trouble with it. I am making a program that will allow the user to pick between a list of text files that are all like this
to search:mirar,buscar
to play:jugar
to be:ser,estar
to run:correr
to make:hacer
to talk:hablar
to take:tomar
to study:estudiar
to arrive:llegar
to practice:practicar
this is the exact format for all of them and i am supposed to put these into a dictionary as key value pairs to make a sort of quiz and ive managed to do that part however i am running into a couple of problems. one is that some of these such as to search for example have multiple correct answers and i dont know how to assign multiple different values to the same key or if thats even possible. and the second problem is that the values have n on the ends of them and i dont know how to remove that. and even if i did, the keys with two options only have the n on the second value.
import os
import sys
def file_open():
file_list=[]
contents=os.listdir()
for i in contents:
if '.txt' in i.lower():
file_list.append(i)
if file_list==[]:
sys.exit('Error')
print('file list:',
file_list)
input_file=str(input('enter the input file to use from the ones above'))
while True:
try:
file=open(input_file,'r')
break
except FileNotFoundError:
print('FileNotFoundError')
return file
def file_read():
dictionary={}
for line in file:
(key,val)=line.split(':')
dictionary[key]=val
return(dictionary)
this is all of the code that i have written out so far and i would appreciate any help or even general advice. Thank you.
Advertisement
Answer
You can store answers of each key into a list, for example:
query_answer={
'to search':['mirar','buscar'],
'to play':['jugar'],
'to be':['ser','estar'], }
Before process the values you should remove ‘n’:
def file_read(file):
dictionary={}
for line in file:
(key,val)=line.split(':')
val = val.rstrip("n")
dictionary[key] = val.split(',')
return dictionary