Mapping words to their palindrome status in a sentence


The code processes a sentence and creates a dictionary named word_is_palindrome using a dictionary comprehension in Python. This dictionary maps words in the sentence to a Boolean value indicating whether each word is a palindrome. Here's a step-by-step explanation of the code:

  • sentence = "madam sees the racecar": This line defines a string variable called sentence containing the sentence "madam sees the racecar."
  • word_is_palindrome = {word: word == word[::-1] for word in sentence.split()}: This line creates the word_is_palindrome dictionary using a dictionary comprehension. Here's how it works:
    • {word: word == word[::-1] for word in sentence.split()} is the dictionary comprehension. It performs the following steps:
    • sentence.split() splits the sentence string into a list of words. In this case, the sentence contains words like "madam," "sees," "the," and "racecar."
    • for word in sentence.split() iterates over each word in the list of words.
    • word == word[::-1] checks if the word is a palindrome. It does this by comparing the word itself (word) to its reverse (word[::-1]).
    • If a word is a palindrome, it creates a key-value pair in the dictionary. The key (word) is the word itself, and the value (word == word[::-1]) is True, indicating that it's a palindrome.
    • If a word is not a palindrome, the value is False.
  • print(sentence): This line prints the original sentence, which is "madam sees the racecar," to the console.
  • print(word_is_palindrome): This line prints the word_is_palindrome dictionary to the console.

Source Code

sentence = "madam sees the racecar"
word_is_palindrome = {word: word == word[::-1] for word in sentence.split()}
print(sentence)
print(word_is_palindrome)

Output

madam sees the racecar
{'madam': True, 'sees': True, 'the': False, 'racecar': True}

Example Programs