-1

my problem is that I need a some variables and parameters which are in string form in dictionary and the values are in both shape (string and integer) For example :

d={'a6':'36','a21':52}

Now I want these to use them in next steps in some math formulas:

a6=36.0
a21=52.0

Is there anyway to change those keys which are in string forms to these variables?

3 Answers3

0

You could just do:

for key,val in d.items():
    vars()[key] = int(val)
>> a6
36
Nakor
  • 1,484
  • 2
  • 13
  • 23
0

You can do it in a single line with:

>>> d = {'a': 1, 'b': 2}
>>> locals().update(d)
>>> a
1

or:

>>> d = {'a':1, 'b':2}
>>> for key,val in d.items():
        exec(key + '=val')

#list(map(exec, ("{0}={1}".format(x[0],x[1]) for x in d.items())))
ncica
  • 7,015
  • 1
  • 15
  • 37
-1

Try:

for k, v in d.items():
    exec("%s = %s" % (k, v))

Please note that using exec (or eval) can create a substantial security risk if you don't have complete control over the inputs.

Rahul Raut
  • 1,099
  • 8
  • 15