Home > Software design >  Creating a Python function that will create a dictionary for tuples of character counts, assigned to
Creating a Python function that will create a dictionary for tuples of character counts, assigned to

Time:11-02

So, trying to create a function that takes a string input, and with that input, it counts all the instances of all characters to a dictionary (like {'a':5, 'b':4 etc..}, and then ultimately creates a new dictionary, that consists of 3 keys: vowels, consonants and others, and adds tuples of character:counts in a set to the correct key.

For example: input 'brown fox'. Return value should be: {'Vowels':{('o', 2)}, 'Consonants':{('b', 1), ('r', 1), ('w', 1), ('n', 1), ('f', 1), ('x', 1)}, 'Other':{' ', 1}}.

Currently I thought it seemed simple through the iteration of keys, but ran to a dead end.

My idea is that I use my function symbol_freq to sort all the unique chars to a dictionary, with the character being the key and value the count. Then I would create a empty dictionary, and start iterating through all of the keys there, seeing if they are in the list of vowels and consonants and assigning tuples of said character to the right key in my new dictionary with 3 keys.

Getting the error of:

Traceback (most recent call last): File "....py", line 26, in print(group("tao pihku ajuhälvik"))

File "....py", line 13, in group for key, value in symbol_freq_dict: ValueError: not enough values to unpack (expected 2, got 1)

def symbol_freq(string):
    symbol_freq_dict = dict.fromkeys(string, 0)
    for i in string:
        symbol_freq_dict[i]  = 1
    return symbol_freq_dict

def group(string):
    vowels = ['a', 'e', 'i', 'o', 'u', 'õ', 'ä', 'ö', 'ü']
    consonants = ['b', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'r', 's', 'š', 'z', 'ž', 't', 'v']
    string.lower()
    symbol_freq_dict = symbol_freq(string)
    grouped_dict = dict()
    for key, value in symbol_freq_dict:
        if key in vowels:
            grouped_dict['Vowels'].append((key, value))
        if key in consonants:
            grouped_dict['Consonants'].append((key, value))
        else:
            grouped_dict['Other'].append((key, value))
            
    return grouped_dict

CodePudding user response:

Read more about dictionaries in python. In a nutshell:

  • They will iterate only over the keys, by default
  • They don't have an append method. (doesn't make since, how you should add something in the end of the dictionary?)

I changed you code as following:

def group(string):
    vowels = ['a', 'e', 'i', 'o', 'u', 'õ', 'ä', 'ö', 'ü']
    consonants = ['b', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'r', 's', 'š', 'z', 'ž', 't', 'v']
    string.lower()
    symbol_freq_dict = symbol_freq(string)
    grouped_dict = {'Vowels': {},'Consonants': {},'Other':{}} # intialized dictionaries
    for key, value in symbol_freq_dict.items(): # added items()
        if key in vowels:
            grouped_dict['Vowels'][key] = value # changed the append
        elif key in consonants:
            grouped_dict['Consonants'][key] = value # changed the append
        else:
            grouped_dict['Other'][key] = value # changed the append

    return grouped_dict

CodePudding user response:

First of all, please read (and post) the full error message, especially the part about what line the error is on.

I am guessing it is the second for loop. Unpacking means, you have a tuple and assign it to two variables at once:

a,b = (1,2) #-> a=1, b=2

You are doing that in the for loop.

For takes each key in the dict and assigns it to the variable on the left. So if you write

for key, value ...

It tries to assign each key of the dict to the two variables, which doesn't work, since it is only one error.

So to fix this, use symbol_freq_dict.enumerate() which retuns basically a list of tuples containing the keys and values.

Btw, next time google your error message.

  • Related