Sum values of a string by assigning values to letters (Python)

Asked

Viewed 71 times

-3

Goal:

Assign values to a string based on a dictionary with keys and values

Example:

I have a string in this format:

str = 'ABCD'

and a dictionary in this.

dic = {'A' : 71, 'B' : 103, 'C' : 115, 'D' : 129}

Script

for i in aa:
    soma += dic.get(i, 0)
print(round(soma, 3))

Problem to be solved:

I need to create a for loop to assign values to str and add. Type 71 + 103 + 115 + 129 and give the final sum value (418) and if I assign n values in the dictionary the program is able to give me the final sum.

Thank you to all who can help....

Leo

  • 1

    Hello Lcalado, Welcome to Stack Overflow in English. In your question you are just sharing an exercise statement. What have you tried? The idea of the site is not to do your college work or homework for you, but if you’re having difficulty somewhere specific, share your code, tell us what you’ve tried to do and what the difficulty is, so you increase your chances of getting a good answer.

  • Thanks Anthony, I’ll do it next time!!! In this case I kept trying to leave the place and I could not, perhaps for the great inexperience, both here in the stack and with the language.

  • print(sum(dic[i] for i in str))

1 answer

2


For the specific case, this solves

str = 'ABCD'
dic = {'A' : 71, 'B' : 103, 'C' : 115, 'D' : 129}

soma = 0
for l in str:
    soma += dic.get(l, 0)
    
    
print(soma)

The above result is 418

The fact of using the dic.get() is in case the letter or other thing is not in the dictionary and in this case the assigned value is 0 (zero)

Example:

str = 'MNOPQ'

As none of the letters are in that dic, the sum result shall be 0 (zero)

  • Thank you Paul, I have already applied here!!!! Very grateful for the explanation!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.