set variable to looping index?

Peter Otten __peter__ at web.de
Wed Jul 29 23:06:30 CEST 2009


Martin wrote:

> I am trying to set the return value from a function to a name which I
> grab from the for loop. I can't work out how I can do this without
> using an if statement...
> 
> for f in var1_fn, var2_fn, var3_fn:
>     if f.split('.')[0] == 'var1':
>         var1 = call_some_function(f)
> .
>         .
>         .
>       etc
> 
>  Really I would like to remove the need for this if loop and I am sure
> there is a simple way I am missing?

Use dictionaries:

functions = {"var1": some_function, "var2": some_other_function, ...} 
return_values = {}

for arg in var1_fn, var2_fn, var3_fn:
    key = arg.split(".")[0]
    return_values[key] = functions[key](arg)

Peter




More information about the Python-list mailing list