0

I have multiple keys mapped to a single value. If any key matches then print the corresponding value. This is only the gist of what I want to do and not the actual code.

responses = {
    ("hi","Yo"):"Lets get started."
}

def get_response(user_message):
    if user_message in responses:
        user_message = responses[user_message]
    print(user_message)

get_response("hi") #should print 'Lets get started'
get_response("Yo") #should print 'Lets get started'

Also is this the right way of storing multiple keys to a single value.

noswear
  • 311
  • 1
  • 6
  • 27
  • Does this answer your question? [How do I make a dictionary with multiple keys to one value?](https://stackoverflow.com/questions/10123853/how-do-i-make-a-dictionary-with-multiple-keys-to-one-value) – sushanth Aug 13 '20 at 11:48
  • @Sushanth I used the mentioned answer to create the dict, but for comparing and retrieving the value I have no clue. – noswear Aug 13 '20 at 11:50

2 Answers2

1

To accomplish what you're trying to do, you would have to check whether "hi" is in the tuple. (("hi", "Yo") is a tuple).

So you can do something like this:

for key in responses:
    if user_message in key:
        print(responses[key])
bensha
  • 69
  • 3
1

You need to modify your get_response method.

responses = {
    ("hi", "Yo"): ["Lets get started."]
}


def get_response(user_message):
    print([values for keys, values in responses.items() if user_message in keys][0][0])


get_response("hi")  # should print 'Lets get started'
get_response("Yo")  # should print 'Lets get started'

Output:

Lets get started.
Lets get started.
Ahmet
  • 7,527
  • 3
  • 23
  • 47