Create a dictionary of words and their reversed forms
This Python code takes a list of words and creates a dictionary reversed_words where the keys are the original words, and the values are the reversed versions of those words. Here's how the code works:
- words = ['apple', 'banana', 'cherry']: This line initializes a list named words with three words.
- reversed_words = {word: word[::-1] for word in words}: This line uses a dictionary comprehension to create the reversed_words dictionary. It iterates through each word word in the words list and assigns a key-value pair to the dictionary. The key is the original word (word), and the value is the word reversed using slicing (word[::-1]).
- for word in words: This part of the code iterates through each word in the words list.
- word[::-1]: This part of the code slices the word with a step of -1, effectively reversing the order of characters in the word.
- print(words): This line prints the original words list to the console.
- print(reversed_words): This line prints the reversed_words dictionary, which contains the original words as keys and their reversed versions as values.
Source Code
words = ['apple', 'banana', 'cherry']
reversed_words = {word: word[::-1] for word in words}
print(words)
print(reversed_words)
Output
['apple', 'banana', 'cherry']
{'apple': 'elppa', 'banana': 'ananab', 'cherry': 'yrrehc'}