Create a dictionary of words and their vowels, excluding words with no vowels


This Python code defines a dictionary vowel_counts, where the keys are words from a list that contain at least one vowel (a, e, i, o, u), and the values are the counts of vowels in each word. Here's how the code works:

  • words = ['apple', 'banana', 'cherry', 'dog', 'ct']: This line initializes a list named words with five string values, some of which contain vowels.
  • vowel_counts = {word: sum(1 for char in word if char.lower() in 'aeiou') for word in words if any(char.lower() in 'aeiou' for char in word)}: This line uses a dictionary comprehension to create the vowel_counts dictionary. It iterates through each word in the words list, and for each word, it checks if there is at least one vowel (any vowel character) in that word.
    • for word in words: This part of the code iterates through each word in the words list.
    • any(char.lower() in 'aeiou' for char in word): This part checks if any character in the word is a lowercase vowel ('a', 'e', 'i', 'o', 'u'). The char.lower() part ensures that both lowercase and uppercase vowels are counted.
    • word: sum(1 for char in word if char.lower() in 'aeiou'): If there is at least one vowel in the word, it creates a key-value pair in the dictionary. The key is the word itself (word), and the value is calculated by summing up 1 for each character in the word that is a vowel. The char.lower() in 'aeiou' part checks if the character is a lowercase vowel.
  • print(words): This line prints the original words list to the console.
  • print(vowel_counts): This line prints the vowel_counts dictionary, which contains words with at least one vowel and their vowel counts.
  • <

Source Code

words = ['apple', 'banana', 'cherry', 'dog', 'ct']
vowel_counts = {word: sum(1 for char in word if char.lower() in 'aeiou') for word in words if
                any(char.lower() in 'aeiou' for char in word)}
print(words)
print(vowel_counts)

Output

['apple', 'banana', 'cherry', 'dog', 'ct']
{'apple': 2, 'banana': 3, 'cherry': 1, 'dog': 1}

Example Programs