Searching for key words in python
Question: If I ask a question in Python and the answer is `chicken`, I want to output
something related to chicken. And, if the answer is `beef` I want to output
something related to beef, dependent on the answer provided.

How could I structure this? Should I have multiple lists with key words and
related answers? Newbie.


Answer: I would use a `dict` of `list`s:

    
    
    import random
    
    similar_words = {
        'chicken': ['poultry', 'wings'],
        'beef': ['cow', 'ground-beef', 'roast-beef', 'steak'],
    }
    
    word = raw_input("Enter a word: ").strip()
    if word in similar_words:
        print random.choice(similar_words[word])
    else:
        print "Not found!"
    

See the Python manual on [Data
Structures](https://docs.python.org/2/tutorial/datastructures.html) for more
information. Note that I'm also using
[`random.choice()`](https://docs.python.org/2/library/random.html#random.choice)
to select a random item from each list.

Here's the output of it running:

    
    
    $ python words.py
    Enter a word: chicken
    poultry
    $ python words.py
    Enter a word: beef
    cow
    $
    

**Edit** : You were asking in the comments how you could do this if the words
were contained inside a whole sentence. Here's one example:

    
    
    words = raw_input("Enter a word or sentence: ").strip().split()
    
    for word in words:
        if word.lower() in similar_words:
            print random.choice(similar_words[word.lower()])
        else:
            print "Not found!"
    

Here, we're using `split()` to split the sentence into a `list` of words. Then
we loop through each word, and see if (the lowercase version of) the word
exists in our `dict`, and do the same thing as we did above with a single
word.

