brayo
brayo

Reputation: 45

How to return python sum values from a dictionary

I have created a dictionary of keys and values,letters each with its own value. Like below:

num = {
    'a': '1',
    'b': '2',
    'c': '3',
    'd': '4',
    'e': '5',
    'f': '6',
    'g': '7',
    'h': '8',
    'i': '9',
    'j': '10',
    'k': '11',
    'l': '12',
    'm': '13',
    'n': '14',
    'o': '15',
    'p': '16',
    'q': '17',
    'r': '18',
    's': '19',
    't': '20',
    'u': '21',
    'v': '22',
    'w': '23',
    'x': '24',
    'y': '25',
 'z': '26'}

I want to take in user input inform of word of . e.g trees`.

Then break it down the into individual letters. Refer to my dictionary then return sum of its values according to the dictionary.

Upvotes: 0

Views: 276

Answers (3)

Sakib Ahammed
Sakib Ahammed

Reputation: 2480

You can do it like:

num = {'a':'1','b':'2','c':'3','d':'4','e':'5','f':'6','g':'7','h':'8','i':'9','j':'10','k':'11','l':'12','m':'13','n':'14','o':'15','p':'16','q':'17','r':'18','s':'19','t':'20','u':'21','v':'22','w':'23','x':'24','y':'25','z':'26'}
name = raw_input("Enter name: ")
L = list(name)

print sum([int(num[i]) for i in L])

Input:

Enter name: mary

Output:

57

Upvotes: 2

Saiful Azad
Saiful Azad

Reputation: 1931

Try it:

di = {'a':'1','b':'2','c':'3','d':'4','e':'5','f':'6','g':'7','h':'8','i':'9','j':'10','k':'11','l':'12', 'm':'13','n':'14','o':'15','p':'16','q':'17','r':'18','s':'19','t':'20','u':'21','v':'22','w':'23','x':'24','y':'25' ,'z':'26'}
p = raw_input()
l = map(int, [di[x] for x in p])
print sum(l)

Upvotes: 0

Niya Simon C
Niya Simon C

Reputation: 299

l = list(input)
print sum([int(num[i] for i in l]) 

Upvotes: 0

Related Questions