Create a dictionary of words and their vowels from a list of strings


This Python code takes a list of words and creates a dictionary vowel_counts where the keys are words, and the values are the counts of vowels (a, e, i, o, u) in each word. Here's how the code works:

  • words = ['apple', 'banana', 'cherry']: This line initializes a list named words with three words.
  • vowel_counts = {word: sum(1 for char in word if char.lower() in 'aeiou') for word in words}: This line uses a dictionary comprehension to create the vowel_counts dictionary. It iterates through each word word in the words list and assigns a key-value pair to the dictionary. The key is the word itself (word), and the value is the result of the following expression:
    • sum(1 for char in word if char.lower() in 'aeiou'): This part of the code counts the number of vowels in each word by iterating through each character char in the word. If char is a vowel (regardless of case), it adds 1 to the count. The sum function calculates the total count of vowels in the word.
    • for word in words: This part of the code iterates through each word in the words list.
  • print(words): This line prints the original words list to the console.
  • print(vowel_counts): This line prints the vowel_counts dictionary, which contains the words as keys and the counts of vowels in each word as values.

Source Code

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

Output

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

Example Programs