Create a dictionary of words and their uppercase forms, excluding words with no uppercase letters


Creates a dictionary named uppercase_words that maps words with at least one uppercase character to their uppercase versions. Here's how the code works:

  • words = ['apple', 'Banana', 'cherry', 'Date']: This line initializes the words list with a collection of words, some of which contain uppercase characters.
  • uppercase_words = {word: word.upper() for word in words if any(char.isupper() for char in word)}: This line uses a dictionary comprehension to create the uppercase_words dictionary. It iterates through each word in the words list and checks if there is at least one uppercase character (char.isupper()) in that word. If the word contains at least one uppercase character, it creates a key-value pair in the dictionary.
    • for word in words: This part of the code iterates through each word in the words list.
    • if any(char.isupper() for char in word): This condition checks if there is at least one uppercase character in the current word. The any function checks if any character in the word is uppercase.
    • {word: word.upper() for word in words if any(char.isupper() for char in word)}: If the condition is met, it creates a key-value pair in the dictionary. The key is the original word, and the value is the uppercase version of that word obtained using word.upper().
  • 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 with at least one uppercase character as keys and their uppercase versions as values.

Source Code

words = ['apple', 'Banana', 'cherry', 'Date']
uppercase_words = {word: word.upper() for word in words if any(char.isupper() for char in word)}
print(words)
print(uppercase_words)

Output

['apple', 'Banana', 'cherry', 'Date']
{'Banana': 'BANANA', 'Date': 'DATE'}

Example Programs