Exercise 104

Write a Python program that asks the user to enter a string, and return him a dictionary whose keys are the characters in the string entered and the values are the number of occurrences of the characters in the string. Example if the entered string is s = 'language', the program returns the dictionary:

d = {'l': 1, 'a': 2, 'n': 1, 'g': 2, 'e': 1}

Solution

# asking user to enter a string  s
s = input ("Enter some string s : ")

# creating an empty dictionary which will contain the string characters and their number of occurrences
d = dict ({})

# browsing through the string characters adding key and values to dictionary
for x in s:
d [x] = s.count(x)

print (d)
# The output for s = 'Python programming' is :
#{'P': 1, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 2, ' ': 1, 'p': 1, 'r': 2, 'g': 2, 'a': 1, 'm': 2, 'i': 1}

Younes Derfoufi
my-courses.net

Leave a Reply