Create a dictionary of strings by repeating each word thrice


Creates a dictionary repeated_words, where the keys are words from a list, and the values are those words repeated three times. Here's how the code works:

  • words = ['apple', 'banana', 'cherry']: This line initializes a list named words with three string values.
  • repeated_words = {word: word * 3 for word in words}: This line uses a dictionary comprehension to create the repeated_words dictionary. It iterates through each word in the words list and creates a key-value pair for each word.
    • for word in words: This part of the code iterates through each word in the words list.
    • 'repeated_words' = {word: word * 3 for word in words}: For each word, it takes the word itself as the key and uses string multiplication (word * 3) to repeat the word three times, creating the value.
  • print(words): This line prints the original words list to the console.
  • print(repeated_words): This line prints the repeated_words dictionary, which contains the words as keys and the words repeated three times as values.

Source Code

words = ['apple', 'banana', 'cherry']
repeated_words = {word: word * 3 for word in words}
print(words)
print(repeated_words)

Output

['apple', 'banana', 'cherry']
{'apple': 'appleappleapple', 'banana': 'bananabananabanana', 'cherry': 'cherrycherrycherry'}

Example Programs