0

I try to define the key of a dictionary as symbol and then I make an expression with those keys. but in the def, there is always show error that said symbol of the key is not defined. but I do debug and it said those symbol of the key is already there.

import sympy as sm

def try_sym(dic):
    for k, v in dic.items():
        exec(k+"=sm.Symbol(k)")

    f = sm.Symbol("f")
    #a=sm.Symbol("a")
    f = a+b
    return f

dic = {"a":1, "b":10}

f =sm.Symbol("f")
f=try_sym(dic)
print(f)
hpaulj
  • 221,503
  • 14
  • 230
  • 353
jmin
  • 15
  • 3
  • why the two conflicting `f=` lines? We don't 'initial' variables in python. – hpaulj Jun 27 '23 at 00:20
  • Be careful - strings, variable names, and `sympy symbols` are different things. What's the purpose of this `dict` and its keys? – hpaulj Jun 27 '23 at 00:54

2 Answers2

0
import numpy as np
import sympy as sm

def try_sym(dic):
    for k, v in dic.items():
        exec(k+"=sm.Symbol(k)")

    f = sm.Symbol("f")
    #a=sm.Symbol("a")
    f = a+b
    return f

dic = {"a":1, "b":10}

f =sm.Symbol("f")
f=try_sym(dic)
print(f)
jmin
  • 15
  • 3
  • it is not the answer.https://stackoverflow.com/questions/1463306/how-to-get-local-variables-updated-when-using-the-exec-call – jmin Jun 26 '23 at 23:47
  • It does, though, explain why `exec` is not working as you want. – hpaulj Jun 27 '23 at 03:04
0

You could stick with a local dict:

In [66]: def try_sym(dic):
    ...:     dd = {k:Symbol(k) for k in dic}
    ...:     f = sum(v for v in dd.values())
    ...:     return f
    ...: 

In [67]: try_sym(dic)
Out[67]: a + b

Using exec as well as creating local and global variables 'dynamically' is generally discouraged. While possible, Python doesn't make it easily.

hpaulj
  • 221,503
  • 14
  • 230
  • 353