1

I am trying to output the sum of consonant and vowel values from a dictionary containing letter_number_pairs as shown below:

vowels = ['a','e','i','o','u']
consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
letter_number_pairs = {'a': 1,'b': 8,'c': 3,'f': 3,'h': 8,'i': 2,'l': 4,'p': 2,'q': 1,'s': 5,'u': 9,'w': 0,'y': 5,'z': 2}

The question I'm wondering is: "Can I sum the vowel values and sum the consonant values in a single pass?" That is, can I avoid executing two passes of the dictionary as shown in my working example below:

vowel_value_sum     = sum(value for (letter, value) in letter_number_pairs.items() if letter in vowels)
consonant_value_sum = sum(value for (letter, value) in letter_number_pairs.items() if letter in consonants)
jpp
  • 159,742
  • 34
  • 281
  • 339
John Forbes
  • 1,248
  • 14
  • 19
  • This stackoverflow question seems similar to what I was trying to achieve: https://stackoverflow.com/questions/9442724/how-to-use-if-else-in-a-dictionary-comprehension – John Forbes Apr 17 '18 at 17:54

3 Answers3

2

Yes, this is possible in a single pass.

Note the inner set inclusion checks are O(1).

a, b = 0, 0

vowels = set(vowels)

for k, v in letter_number_pairs.items():
    if k in vowels:
        a += v
    else:
        b += v

print([a, b])

# [12, 41]
jpp
  • 159,742
  • 34
  • 281
  • 339
2

Simply restructure your vowels and consonants data:

letters = {'vowels':['a','e','i','o','u'], 'consonants':['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']}
letter_number_pairs = {'a': 1,'b': 8,'c': 3,'f': 3,'h': 8,'i': 2,'l': 4,'p': 2,'q': 1,'s': 5,'u': 9,'w': 0,'y': 5,'z': 2}
final_sums = {a:sum(letter_number_pairs.get(i, 0) for i in b) for a, b in letters.items()}

Output:

{'vowels': 12, 'consonants': 41}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
1

If you want in one iteration then you can try this approach:

vowels = ['a','e','i','o','u']
consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
letter_number_pairs = {'a': 1,'b': 8,'c': 3,'f': 3,'h': 8,'i': 2,'l': 4,'p': 2,'q': 1,'s': 5,'u': 9,'w': 0,'y': 5,'z': 2}

vowel_sum=[]
conso_sum =[]
for i in letter_number_pairs:
    if i in vowels:
        vowel_sum.append(letter_number_pairs[i])
    elif i in consonants:
        conso_sum.append(letter_number_pairs[i])
    else:
        pass    #in case of special characters


print(sum(vowel_sum))
print(sum(conso_sum))

output:

12
41
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88