Create a dictionary of words and their uppercase forms


This Python code takes a list of words and creates a dictionary uppercase_words where the keys are the words from the original list, and the values are the uppercase versions of those words. Here's how the code works:

  • words = ['apple', 'banana', 'cherry']: This line initializes a list named words with three string values.
  • uppercase_words = {word: word.upper() for word in words}: This line uses a dictionary comprehension to create the uppercase_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 uppercase version of the word (word.upper()).
    • for word in words: This part of the code iterates through each word in the words list.
    • word: word.upper(): This part of the code creates the key-value pair. The key is the original word, and the value is the uppercase version of the word.
  • print(words): This line prints the original words list to the console.
  • print(uppercase_words): This line prints the uppercase_words dictionary, which contains words as keys and their uppercase versions as values.

Source Code

words = ['apple', 'banana', 'cherry']
uppercase_words = {word: word.upper() for word in words}
print(words)
print(uppercase_words)

Output

['apple', 'banana', 'cherry']
{'apple': 'APPLE', 'banana': 'BANANA', 'cherry': 'CHERRY'}

Example Programs