Create a dictionary of strings with words containing "a" and their lengths


Creates a dictionary a_word_lengths, where the keys are words from a list that contain 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 'a' in word}: This line uses a dictionary comprehension to create the a_word_lengths dictionary. It iterates through each word in the words list, checks if the letter 'a' is in the word, and creates a key-value pair for words that contain '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 'a' in word}: For each word, it takes the word itself as the key and uses the len(word) function to calculate the length of the word, creating the value.
    • if 'a' in word: This condition ensures that only words containing the letter 'a' are included in the dictionary.
  • 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 (with 'a') as keys and their respective lengths as values.

Source Code

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

Output

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

Example Programs