Use a function in mydict [variable]. KeyError: <function myfunction at 0x7f6b65a0f7f0>

Question:

Until now I used a dictionary and a variable in the following way and it worked correctly:

if mydict[variable] == value:

Now I would like to replace the variable with the return of a function. I tried to write like this

if mydict[myfunction] == value 

but I get an error:

KeyError: <function myfunction at 0x7f6b65a0f7f0>

How can I solve?

Asked By: DavidGr92

||

Answers:

You need to invoke the function (ie. make it run).

You do this by putting () after the function name.. myFunction()

if mydict[myfunction()] == value

What you had done is pass a reference to the function and tried to use that as a key in your dictionary rather than passing the result returned by your function and using that as a key.

Answered By: Richard Plester
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.