Mapping words to their frequency of containing the letter "e"


The code processes a sentence and creates a dictionary named word_contains_e using a dictionary comprehension in Python. This dictionary maps words in the sentence to the count of the letter 'e' in each word. Here's a step-by-step explanation of the code:

  • sentence = "Hello, how are you?": This line defines a string variable called sentence containing the sentence "Hello, how are you?"
  • word_contains_e = {word: word.count('e') for word in sentence.split()}: This line creates the word_contains_e dictionary using a dictionary comprehension. Here's how it works:
    • {word: word.count('e') for word in sentence.split()} is the dictionary comprehension. It performs the following steps:
    • sentence.split() splits the sentence string into a list of words. In this case, it will include words like "Hello," (with a comma) and "you?" (with a question mark).
    • for word in sentence.split() iterates over each word in the list of words.
    • word.count('e') counts the occurrences of the letter 'e' in the word.
    • It creates a key-value pair in the dictionary, where the key (word) is the word itself, and the value (word.count('e')) is the count of the letter 'e' in the word.
  • print(sentence): This line prints the original sentence, which is "Hello, how are you?", to the console.
  • print(word_contains_e): This line prints the word_contains_e dictionary to the console.

Source Code

sentence = "Hello, how are you?"
word_contains_e = {word: word.count('e') for word in sentence.split()}
print(sentence)
print(word_contains_e)

Output

Hello, how are you?
{'Hello,': 1, 'how': 0, 'are': 1, 'you?': 0}

Example Programs