Map function and Dictionary in Python to sum ASCII values

PythonProgrammingServer Side Programming

We want to calculate the ASCII sum for each word in a sentence and the sentence as a whole using map function and dictionaries. For example, if we have the sentence −

"hi people of the world"

The corresponding ASCII sums for the words would be : 209 645 213 321 552

And their total would be : 1940.

We can use the map function to find the ASCII value of each letter in a word using the ord function. Then using the sum function we can sum it up. For each word, we can repeat this process and get a final sum of ASCII values.


 Live Demo

sent = "hi people of the world"
words = sent.split(" ")

result = {}

# Calculate sum of ascii values for every word
for word in words:
result[word] = sum(map(ord,word))

totalSum = 0
# Create an array with ASCII sum of words using the dict
sumForSentence = [result[word] for word in words]

print ('Sum of ASCII values:')
print (' '.join(map(str, sumForSentence)))

print ('Total of all ASCII values in sentence: ',sum(sumForSentence))


This will give the output −

Sum of ASCII values:
209 645 213 321 552
Total of all ASCII values in a sentence: 1940
Published on 03-Aug-2018 10:57:55