Create a dictionary of words and their lengths from a sentence


This Python code creates a dictionary named word_lengths where the keys are words from a sentence, and the values are the lengths of those words. Here's how the code works:

  • sentence = "Python is awesome": This line initializes a string variable named sentence with the sentence you want to analyze.
  • word_lengths = {word: len(word) for word in sentence.split()}: This line uses a dictionary comprehension to create the word_lengths dictionary. It splits the sentence into words using .split() and iterates through each word in the sentence. For each word, it assigns a key-value pair to the dictionary. The key is the word itself (word), and the value is the length of that word (len(word)).
    • for word in sentence.split(): This part of the code iterates through each word in the sentence after splitting it into words.
  • print(sentence): This line prints the original sentence to the console.
  • print(word_lengths): This line prints the word_lengths dictionary, which contains the lengths of words from the original sentence.

Source Code

# sentence=input("Enter String : ")
sentence = "Python is awesome"
word_lengths = {word: len(word) for word in sentence.split()}
print(sentence)
print(word_lengths)

Output

Python is awesome
{'Python': 6, 'is': 2, 'awesome': 7}

Example Programs