Belkin
Belkin

Reputation: 3

How to get value for each string index matching key in dictionary in Python

str = 'strings'

new_D = {'r': 1, 's': 1, 't': 1, 'r' : 3, 'i' : 4 }

How can I get each letter in the string assigned to the value in the dictionary by match 'letter-key' and then summarize the values?

Thanks

Upvotes: 0

Views: 617

Answers (2)

NightShadeQueen
NightShadeQueen

Reputation: 3335

s = 'strings' #Don't name a variable str, that shadows the builtin str

new_D = {'r': 1, 's': 1, 't': 1, 'r' : 3, 'i' : 4 }

sum_of_chars = sum([newD.get(k,0) for k in s]) #assuming 0 as default for "not in dictionary"

This takes advantage of the fact that:

  1. Strings are iterable. for i in s: print(i) would print each character, seperately.
  2. Dictionaries have a .get(key[,default]) 1 that can take an option argument for "return this value if the key doesn't exist.
  3. I'm using the built-in sum on a list comprehension for the sake of brevity. Brevity can both be a virtue or a vice, but, hey, one list comp is still usually pretty readable after you know what they are.

Upvotes: 1

Felix
Felix

Reputation: 6359

string = 'strings'

new_D = {'r': 1, 's': 1, 't': 1, 'r' : 3, 'i' : 4 }

sum_of_chars = 0
for character in string:
    if character in new_D:
        sum_of_chars += new_D[character]
    else:
        sum_of_chars += 1 # Default?

print(sum_of_chars)

btw, you should not use the name str because it shadows the builtin str and there's a mistake in your dictionary. It contains the entry r two times which doesn't make sense.

Upvotes: 0

Related Questions