Mapping words to their reverse in a sentence


The code processes a sentence and creates a dictionary named word_reverse_mapping using a dictionary comprehension in Python. This dictionary maps words in the sentence to their respective reversed versions. Here's a step-by-step explanation of the code:

  • sentence = "Hello, how are you?": This line defines a string variable called sentence containing the sentence "Hello, how are you?"
  • word_reverse_mapping = {word: word[::-1] for word in sentence.split()}: This line creates the word_reverse_mapping dictionary using a dictionary comprehension. Here's how it works:
    • {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, it will include words like "Hello," (with a comma) and "you?" (with a question mark).
    • for word in sentence.split() iterates over each word in the list of words.
    • word[::-1] reverses the order of characters in the word. This is achieved by using Python's slicing notation, where [::-1] is used to reverse a string.
    • It creates a key-value pair in the dictionary, where the key (word) is the word itself, and the value (word[::-1]) is the word reversed.
  • print(sentence): This line prints the original sentence, which is "Hello, how are you?", to the console.
  • print(word_reverse_mapping): This line prints the word_reverse_mapping dictionary to the console.

Source Code

sentence = "Hello, how are you?"
word_reverse_mapping = {word: word[::-1] for word in sentence.split()}
print(sentence)
print(word_reverse_mapping)

Output

Hello, how are you?
{'Hello,': ',olleH', 'how': 'woh', 'are': 'era', 'you?': '?uoy'}

Example Programs