How to select random key with common values?

Firs thing you need is your initial dictionary with only hi. Then we say something to our friend. We check all the values, if our phrase is not in there, we ask for the phrase to be defined. We create a new key with that definition along with a default empty list. We then append the phase to that list. Else, we search which value list our phrase lies in and select a random word from that list.

from random import choice

knowledge = {'hi': ['hi']}
while True:
    new = input('Say something to HAL: ')
    check = list(*knowledge.values())
    if new.lower() not in check:
        key = input('Define {} for me: '.format(new))
        knowledge.setdefault(key.lower(), [])
        knowledge[key].append(new.lower())
    else:
        for k, v in knowledge.items():
            if new.lower() in v:
                print(choice(v).title())
Say something to HAL: hi 
Hi
Say something to HAL: hey
Define hey for me: hi
Say something to HAL: hey
Hey
Say something to HAL: hey
Hi

Leave a Comment