nested dictionaries and functions in data structures.

Frank Millman frank at chagford.com
Tue Jan 7 06:46:57 EST 2014


"Sean Murphy" <mhysnm1964 at gmail.com> wrote in message 
news:0CF6151E-E063-4252-9AC3-4FD4698EB28C at gmail.com...
> Hello all.
>
> I have some questions again. :-)
>
> I wish to be able to place a function within a data structure. I would 
> like to use a dictionary because I could pass it a key and then the 
> function could be called. I  couldn't find anything on the net to show me 
> how to do this. More then likely, not using the right search terms.
>
> For example:
>
> funct_call = { 'bhp' : 'bhp_counters (addict[key1][key2])', 'ospf' : 
> 'ospf_counters (addict[key1][key2])'}
>
> I am sure there is a way to do this.
>
[...]

There are two problems with your example.

First, it is (probably) correct to enclose the key in quotes, but definitely 
incorrect to enclose the function name in quotes. Assuming you have already 
declared the function, you just use the function name, without quotes, as 
the value.

Secondly, you must not place brackets, with or without arguments, after the 
function name. The difference is that, without brackets it *refers* to the 
function, with brackets it *calls* the function. You only want to call it at 
execution time, not when setting up the dictionary.

If you have a variable 'var' which contains 'bhp' or 'ospf', you would at 
execution time have the following -
    funct = funct_call[var]  # retrieve the function from the dictionary
    funct(addict[key1][key2])  # call the function with arguments

This is usually compressed into one line -
    funct_call[var](addict[key1][key2])

This works if you always use the same arguments, no matter which function 
you call. Things get trickier if they differ.

Frank Millman






More information about the Python-list mailing list