Home > Enterprise >  How to pass in arguments to a function (a dictionary item) inside the dictionary.get() method in Pyt
How to pass in arguments to a function (a dictionary item) inside the dictionary.get() method in Pyt

Time:07-02

I'd like to replace multiple if ... else statements with a dictionary. The following code runs successfully and outputs 7 (i.e. the first argument is 'add' which calls the add function declared inside the my_dict dictionary and gives it the arguments n1 and n2):

def my_calc(operation, n1, n2):

    my_dict = {
        'add': lambda n1, n2: n1   n2,
        'sub': lambda n1, n2: n1 - n2,
        'mul': lambda n1, n2: n1 * n2,
        'div': lambda n1, n2: n1 / n2
    }

    return my_dict[operation](n1, n2)

print(my_calc('add', 3, 4))

However, if I try to pass in an unfamiliar argument e.g. my_calc('abc', 3, 4), it raises a KeyError because abc is not defined. For that reason, I'm using the dictionary.get() method.

How do I pass in arguments to a function returned by the get() method from a dictionary? The function should return the result of the operation performed on n1 and n2. I could easily have handled the error using try ... except but I'd like to do it using the dictionary.get() method and have the function return a default value if the operation is not in the dictionary.

def my_calc(operation, n1, n2):

    my_dict = {
        'add': lambda n1, n2: n1   n2,
        'sub': lambda n1, n2: n1 - n2,
        'mul': lambda n1, n2: n1 * n2,
        'div': lambda n1, n2: n1 / n2
    }
    
    return my_dict.get(operation(n1, n2), "Default Value")

print(my_calc('abc', 3, 4))

Output:

Traceback (most recent call last):
  File "<string>", line 12, in <module>
File "<string>", line 10, in my_calc
TypeError: 'str' object is not callable

Is there any way I could pass in the arguments to the operation inside the get() method?

List item

CodePudding user response:

Your first problem is that you're calling the operation, which is a string. You want to call the result of the get() method instead. That means the arguments go outside (after) the get() parentheses.

Then, to provide a default behavior, the default value in get() should also be a function. It just doesn't need to do anything with its arguments. You can use a lambda like you have for the others.

return my_dict.get(operation, lambda n1, n2: "Default Value")(n1, n2)

If you want, you can store the default function in your dictionary. That way they're all together. We'll use None as the key since that 1) makes sense (there is no operation) and 2) can never be entered by a user.

my_dict = {
    None:  lambda n2, n2: "Default value",
    'add': lambda n1, n2: n1   n2,
    'sub': lambda n1, n2: n1 - n2,
    'mul': lambda n1, n2: n1 * n2,
    'div': lambda n1, n2: n1 / n2
}

Then...

return my_dict.get(operation, my_dict[None])(n1, n2)
  • Related