Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I look up a string in a dictionary which has tuples of strings for its keys?

I have this code:

import random
greetings_commands = ('hello', 'hi', 'hey')
compliment_commands = (' you look great', 'you are so good', 'you are amazing')

greetings_responses = ['hi sir', 'hello sir', 'hey boss']
compliment_responses = ['so as you sir', 'thanks, and you look beautiful', 'thanks sir']

commands_list = {greetings_commands: greetings_responses, compliment_commands: compliment_responses}

while True:
  user_input = input('Enter your message: ')   # user input or command or questions
  if user_input in commands_list: # check if user_input in the commands dictionary keys
    response = random.choice(commands_list[user_input]) # choose randomly from the resonpses list
    print(response) # show the answer

Right now, the if user_input in commands_list condition is not met, and no response is printed.

How can I make it so that if user_input is found in any of the tuples used for the dictionary keys, a response is chosen from the corresponding value in the dictionary?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Iterate through the keys and values of the dictionary, choosing a response once you find a key that contains the user input.

while True:
  user_input = input('Enter your message: ')   # user input or command or questions
  for commands, responses in commands_list.items():
    if user_input in commands:
      response = random.choice(responses) # choose randomly from the resonpses list
      print(response) 
      break
    

Alternatively expand commands_list so that each key is a single command, to make look-up easier:

commands_list = {command: responses 
  for commands, responses in commands_list.items() 
  for command in commands}

Then your current code will work.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading