Create a dictionary of strings with words containing more than 4 letters


The Python code pocesses a sentence and creates a dictionary named long_words. This dictionary maps words with a length greater than 4 to their respective lengths. Here's how the code works:

  • sentence = "Python is a powerful and versatile programming language": This line initializes the sentence variable with a string containing words.
  • long_words = {word: len(word) for word in sentence.split() if len(word) > 4}: This line uses a dictionary comprehension to create the long_words dictionary. It splits the sentence into words using sentence.split(), then iterates through each word in the list of words.
    • for word in sentence.split(): This part of the code iterates through each word in the sentence.
    • if len(word) > 4: This condition checks if the length of the current word is greater than 4 characters.
    • {word: len(word)}: If the condition is met, it creates a key-value pair in the dictionary. The key is the word itself, and the value is the length of the word obtained using len(word).
  • print(sentence): This line prints the original sentence to the console.
  • print(long_words): This line prints the long_words dictionary, which contains words with a length greater than 4 as keys and their respective lengths as values.

Source Code

sentence = "Python is a powerful and versatile programming language"
long_words = {word: len(word) for word in sentence.split() if len(word) > 4}
print(sentence)
print(long_words)

Output

Python is a powerful and versatile programming language
{'Python': 6, 'powerful': 8, 'versatile': 9, 'programming': 11, 'language': 8}

Example Programs