Create a dictionary of strings by replacing vowels with underscores


The Python code defines a dictionary underscored_words, where the keys are words from a list, and the values are the same words with vowels replaced by underscores. Here's how the code works:

  • words = ['apple', 'banana', 'cherry']: This line initializes a list named words with three string values.
  • underscored_words = {word: ''.join(['_' if char.lower() in 'aeiou' else char for char in word]) for word in words}: This line uses a dictionary comprehension to create the underscored_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.
    • ''.join(['_' if char.lower() in 'aeiou' else char for char in word]): For each word, it creates a modified version of the word with vowels replaced by underscores ('_'). It does this by iterating through each character in the word (for char in word) and using a conditional expression to check if the character is a lowercase vowel ('a', 'e', 'i', 'o', 'u'). If it's a vowel, it replaces it with an underscore; otherwise, it keeps the character as it is. The join method is used to concatenate the modified characters back into a single string.
  • print(words): This line prints the original words list to the console.
  • print(underscored_words): This line prints the underscored_words dictionary, which contains the original words as keys and their vowel-replaced versions as values.

Source Code

words = ['apple', 'banana', 'cherry']
underscored_words = {word: ''.join(['_' if char.lower() in 'aeiou' else char for char in word]) for word in words}
print(words)
print(underscored_words)

Output

['apple', 'banana', 'cherry']
{'apple': '_ppl_', 'banana': 'b_n_n_', 'cherry': 'ch_rry'}

Example Programs