[Tutor] Can a method be added to dictionary?

John Fouhy john at fouhy.net
Fri Nov 20 01:22:48 CET 2009


2009/11/20  <lauren at protopc.com>:
> Hey Gang,
>
> Can a function/method be added to a dictionary like so:
>
> myDictionary = {"string":processString(parameter),
>                "string2":processString2(parameter),
>                "string3":processString3(parameter)
>               }
>
> I am basically interested in doing this with a Combobx Event.
> When the user selects an option in my dropdown box (event.GetString())
> that matches the string in my dictionary...say "string2" then the method:
> processString2(parameter) is executed.
>
> Currently when I get the value of: myDictionary[string2] it is None.
>
> Thanks for your help!
> Lauren

Hi Lauren,

What happens here is that "processString2(parameter)" executes at the
point you define the dictionary.  So myDictionary[string2] is None
because that's what your method returns.

What you need to do is put an actual function in there, instead of a
function call.

Here's a toy example:
>>> def say_hello():
...     print 'Hello world!'
...
>>> myDict = { 1:say_hello }  # note: no () here!
>>> myDict[1]
<function say_hello at 0x4638f0>
>>> myDict[1]()               # now I use () to call the function.
Hello world!

Hope this helps!

-- 
John.


More information about the Tutor mailing list