Skip to content
Advertisement

Is there way to have function parameters be used to call on dictionary keys?

I have a dictionary with numerical values assigned to elements of the periodic Table. I’d like to have a function where I can have one of the parameters as one of the elements so that a user can do calculation just with the inputting parameters.

This is what I had so far

ele={"H":3, "He":7, "O":9}

def func(x,y,z,d)
    i=ele["x"]*y + ele["z"]*d
    return i
func("H", 2, "O", 3)
print(i)
    

For i I’d want to see 33 but it doesn’t even get that far. I keep getting a KeyError for x.

Advertisement

Answer

Karim!

When you place any text between quotes it is considered a string, not a variable. Because of that, your code tells python to look for the key “x” in the elements dictionary (in the variable ele). Since there is no x key on it, python raises a KeyError exception.

All you have to do is get rid of the quotes.

ele={"H":3, "He":7, "O":9}

def func(x,y,z,d)
    i=ele[x]*y + ele[z]*d
    return i

print(func("H", 2, "O", 3))

Please note that you can’t print the content of the variable “i” from outside function “func” since it is a local variable. Printing function “func” directly will do what you intended to do, as long as that function returns “i”.

Advertisement