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

Question:

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?

Asked By: Ibrahim Ali

||

Answers:

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.

Answered By: Stuart
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.