Exercise 110

Write a Python program that asks the user to enter a text and return a dictionary whose keys are the words of the text entered and the values are the lengths of the words that make up the text. Example for the text T = "Python is a programming language", the program must return the dictionary:

d = {'Python': 6, 'is': 3, 'a': 3, 'language': 7, 'de': 2, 'programming': 13}

Solution

# ask user to type a text
T = input("Type a some text")
# convert the text to list of words
listWords = T.split(' ')
# create an empty dictionary which will contains the words contained in the text
d= dict({})

for word in listWords:
d[word] = len(word)

# display obtained dictionary d
print("The obtained dictionary is d = " , d)
# If typed text is T = "Python is programming language", the output is :
#The obtained dictionary is d = {'Python': 6, 'is': 2, 'programming': 11, 'language': 8}

Younes Derfoufi
my-courses.net

Leave a Reply