Create a dictionary of strings with words in reverse order


The Python code processes a sentence and creates a dictionary named reversed_words. This dictionary maps each word's index (position) in reverse order to the word itself. Here's how the code works:

  • sentence = "Python is fun": This line initializes the sentence variable with a string containing multiple words.
  • reversed_words = {i: word for i, word in enumerate(sentence.split()[::-1])}: This line uses a dictionary comprehension to create the reversed_words dictionary. Here's what happens:
    • sentence.split(): This part of the code splits the sentence into individual words and returns a list of words.
    • [::-1]: This part reverses the order of the words in the list. So, it effectively reverses the word order in the sentence.
    • enumerate(...): This function is used to iterate through the reversed list of words, and it returns both the index (i) and the word itself.
    • {i: word for i, word in ...}: This part of the code creates key-value pairs in the dictionary. The keys (i) are the indices of the words, and the values (word) are the individual words from the reversed list.
  • print(sentence): This line prints the original sentence, sentence, to the console.
  • print(reversed_words): This line prints the reversed_words dictionary, which contains word indices as keys (in reverse order) and the corresponding words as values.

Source Code

sentence = "Python is fun"
reversed_words = {i: word for i, word in enumerate(sentence.split()[::-1])}
print(sentence)
print(reversed_words)

Output

Python is fun
{0: 'fun', 1: 'is', 2: 'Python'}

Example Programs