Search code examples
pythondictionaryinputchatbot

Dictionary and Input: if the `input` contains any of the keys I want to print the value


I'm trying to build kind of a simple chatbot, but when the input is something out of the dictionary the else block is working as it should be...

I want to print the value even if the input is something from the keys and some other words. for example:

text something: hi there answer: hello

so, if the input contains any of the keys i want to print the value.

please let me know if you know a way to make this. Thank you.

words = {"good night": ["nighty night", "good night", "sleep well"],
         "good morning": ["good morning", "wakey-wakey!", "rise and shine!"],
         "hi": ["hello", "hey", "hola"]
         }


text_punk = input("text something: ")

if text_punk in words:
    punk = random.choice(words[text_punk])

    print(punk)
    talk(punk) #this is for pyttsx3
else:
    print("problem!")

Solution

  • you can do the following.

    import random
    words = {"good night": ["nighty night", "good night", "sleep well"],
             "good morning": ["good morning", "wakey-wakey!", "rise and shine!"],
             "hi": ["hello", "hey", "hola"]
             }
    
    text_punk = input("text something: ")
    
    greet_words = words.keys() #check if your key words is in input_text.
    word_available = [word for word in greet_words if word in text_punk]
    
    if word_available: # if words are available take the first of key.
        punk = random.choice(words[word_available[0]])
    
        print(punk)
        talk(punk) #this is for pyttsx3
    else:
        print("problem!")