python - Can I use a dictionary in this way -


i'm revising gcse coursework. task have been asked troubleshooting program, in user says problem; , evaluate input , test keywords, before pulling text file code , printing according solution.

this original code:

keywords = ["k1","k2","k3","k4","k5","k6","k7","k8","k9","kk"]  question_about_phone = input("what seems problem? please percific don't bombard info").lower()  file = open('code.txt','r') solution = [line.strip(',') line in file.readlines()]  x in range(0, 10):      if keywords[x] in question_about_phone:         print(solution[x]) 

however in middle of assessment realised u cant have printing solution each keyword. decided make assign value different list , have many lines of

if list[1] , list[5] = "true:  print(solution[1] 

and on ...

however inefficient ;( there anyway can use dictionary values , along lines of:

dictionary = [list[1] list[5], (more combos) (probably while loop)

for x in range(0,10):     if dictionary[x] == "true":         print(solutions[x])         end code 

you can do

keywords = ["battery", "off", "broken"] question_about_phone = input("what seems problem?")  open('code.txt', 'r') file:     solutions = {k:line.strip(',\n') k, line in zip(keywords, file)}     answers = [v k, v in solutions.items() if k in question_about_phone]  if answers:     print(answers) else:     print('sorry, there no answers question') 

which, example, file of

answer 4 battery answer 4 off answer 4 broken ... 

and input question of

what seems problem? broken battery sunny 

produces

['answer 4 broken', 'answer 4 battery'] 

basically solutions built pairing keywords , each line of file.

then answers formed picking values of keywords appear in question

however, agree tim seed's approach: more efficient keywords present in question instead of doing opposite, since possible answers outnumber terms in question.

in order achieve that, change

answers = [solutions[k] k in question_about_phone.split() if k in solutions] 

Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

json - Gson().fromJson(jsonResult, Myobject.class) return values in 0's -