Create a dictionary of words and their lengths, but only for words with more than 5 letters


This Python code takes a list of words and creates a dictionary long_word_lengths where the keys are words with lengths greater than 5 characters, 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 words.
  • long_word_lengths = {word: len(word) for word in words if len(word) > 5}: This line uses a dictionary comprehension to create the long_word_lengths dictionary. It iterates through each word word in the words list and assigns a key-value pair to the dictionary only if the length of the word is greater than 5 characters. The key is the word itself (word), and the value is the length of the word (computed using len(word)).
    • for word in words: This part of the code iterates through each word in the words list.
    • if len(word) > 5: This part of the code checks if the length of the current word is greater than 5.
  • print(words): This line prints the original words list to the console.
  • print(long_word_lengths): This line prints the long_word_lengths dictionary, which contains the words with lengths greater than 5 as keys and their respective lengths as values

Source Code

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

Output

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

Example Programs