Dynamic variable creation from string

MRAB python at mrabarnett.plus.com
Wed Dec 7 13:07:47 EST 2011


On 07/12/2011 17:45, John Gordon wrote:
> In<b078a04b-024b-48dc-b24a-8f4ce75fa238 at 13g2000vbu.googlegroups.com>  Massi<massi_srb at msn.com>  writes:
>
>> in my script I have a dictionary whose items are couples in the form
>> (string, integer values), say
>
>> D = {'a':1, 'b':2, 'c':3}
>
>> This dictionary is passed to a function as a parameter, e.g. :
>
>> def Sum(D) :
>>      return D['a']+D['b']+D['c']
>
>> Is there a way to create three variables dynamically inside Sum in
>> order to re write the function like this?
>
> Do you want to sum all the values in D?  If so, that's easy:
>
>    def Sum(D):
>        my_sum = 0
>        for item in D:
>            my_sum += D[item]
>        return my_sum
>
Or even:

def Sum(D):
     return sum(D.values())



More information about the Python-list mailing list