How to add to a value in a dictionary when a tuple is the key?

Viewed 19

So what I am currently trying to do is take a list of letters and find out how many vowels there are, both lower-case and upper-case count as a lower-case entry in the dictionary, and add 1 to that respective tuple in my dictionary. I'm unable to use string or list methods so I figured a dictionary with tuples as keys would work best given these restrictions.

def vowels_count(letters):
    vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
    frequent = {('a', 'A') : 0, ('e', 'E') : 0, ('i', 'I') : 0, ('o', 'O') : 0, ('u', 'U') : 
    0}
    for i in letters:
        if i in vowels:
1 Answers

To answer your specific case:

def vowels_count(letters):
    vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
    frequent = {('a', 'A') : 0, ('e', 'E') : 0, ('i', 'I') : 0, ('o', 'O') : 0, ('u', 'U') : 
    0}
    for i in letters:
        if i in vowels:
           frequent[(i.lower(), i.upper())] += 1
    return frequent

However to suggest another way of doing it if you dont need the resulting dictionary to be a tuple:

import re
import collections

def vowels_count(letters: str) -> dict[str, int]:
    vowels = re.sub('[^aeiou]', '', letters.lower())
    return dict(collections.Counter(vowels))
Related