Create a dictionary of words and their lengths, but only for words starting with a


The Python code you provided creates a dictionary a_word_lengths, where the keys are words from a list that start with the letter 'a', and the values are the lengths of those words. Here's how the code works:

  • words = ['apple', 'banana', 'cherry', 'date']: This line initializes a list named words with four string values.
  • a_word_lengths = {word: len(word) for word in words if word.startswith('a')}: This line uses a dictionary comprehension to create the a_word_lengths dictionary. It iterates through each word in the words list and creates a key-value pair for each word that starts with the letter 'a'.
    • for word in words: This part of the code iterates through each word in the words list.
    • 'a_word_lengths' = {word: len(word) for word in words if word.startswith('a')}: For each word, it checks if the word starts with the letter 'a' using the word.startswith('a') condition. If the condition is true, it includes the word in the dictionary. The key is the word itself, and the value is the length of the word, calculated using the len(word) function.
  • print(words): This line prints the original words list to the console.
  • print(a_word_lengths): This line prints the a_word_lengths dictionary, which contains the words starting with 'a' as keys and their corresponding lengths as values.

Source Code

words = ['apple', 'banana', 'cherry', 'date']
a_word_lengths = {word: len(word) for word in words if word.startswith('a')}
print(words)
print(a_word_lengths)

Output

['apple', 'banana', 'cherry', 'date']
{'apple': 5}

Example Programs