[Tutor] using a function as a dictionary value?

Liam Clarke cyresse at gmail.com
Mon Dec 13 11:44:08 CET 2004


Hey Justin,

Tricky one this..

as far as I know, and I'm a beginner myself, a dictionary stores a
reference to the function, not the actual function.

So - 

> command = {'1': spam(),
>             '2': breakfast(),
>             '3': bridgekeeper()
>             }

Try this instead - 

command = {'1': spam, '2':breakfast, '3': bridgekeeper}



and

> select = raw_input('Chose an option [1|2|3]: ')
> 
> options = ['1', '2', '3']

> 
> if select in options:
>     command[select]

change this to - 

select = raw_input('Chose an option [1|2|3]: ')

if select in command.keys():
     command[select]()



That one had me going round in circles when I first met it.
AFAIK, everything is stored in dictionaries apparently. If you have a
function called 'dude()' you could probably call it as a dictionary of
'dude' from the namespace...

Standard disclaimer - 

Someone more knowledgable would probably be along shortly to point out
a simpler, elegant way to do it, but my way works. Mostly.

HTH

Liam Clarke




> #####
> def spam():
>     print 'Hello world'
> 
> def breakfast():
>     print 'Spam, Spam, Chips, and Spam'
> 
> def bridgekeeper():
>     print 'Ask me your questions, Bridgekeeper. I am not afraid.'
> 
> select = raw_input('Chose an option [1|2|3]: ')
> 
> options = ['1', '2', '3']

> 
> if select in options:
>     command[select]
> 
> else:
>     print 'Selection not recognized.'
> #####
>


'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.


More information about the Tutor mailing list