Python Forum

Full Version: Sum char word dictionary
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a dictionary that gives me a letter of the alphabet as a key and a number that corresponds to the position of the letter of the alphabet.
Quote:{'a':1 'b':2 ... 'z':26}
I would like that if I take a string, make the sum of the individual values.
I created the dictionary to do it, but I don't know how to do the sum inside the dictionary because it's not a string.


To better understand what I want:

Quote: example : l + o + v + e = 54
list_alphabet = {} 
alpha = 'a' #first letter in alphabet
for i in range(0,26):
    list_alphabet[alpha] = i +1
    alpha = chr(ord(alpha)+1)
print(list_alphabet)

# for break word --> use split() ?

Never mind I resolved!!!
def wordsToMarks(word):
  res = 0
  list_alphabet = {} 
  alpha = 'a' #first letter in alphabet
  for i in range(0,26):
    list_alphabet[alpha] = i +1
    alpha = chr(ord(alpha)+1)
  
  for letter in word:
    res += list_alphabet.get(letter,0)
  return res

word = 'love'
print(wordsToMarks(word))
What about uppercase chars?

One can take advantage of fact that lowercase ascii letters codepoints are 97-122. Just deduct 96 from codepoint value:

>>> sum(ord(char)-96 for char in 'love')
54
Of course one should be defensive (what should happen if letters not in this range are encountered like uppercase etc)
I don't know maybe I should check it but how do I do it?
One way is to check range (just ignoring everything else):

>>> sum(ord(char) - 96 for char in 'love' if ord(char) in range(97, 123))
54
As one can observe we do ord(char) twice, so in Python 3.8 we can take advantage of walrus operator:

>>> sum(codepoint - 96 for char in 'love' if (codepoint := ord(char)) in range(97, 123))
54
Alternatively we can move calculation into if condition:

>>> sum(codepoint for char in 'love' if (codepoint := ord(char) - 96) in range(1, 27))
54