M
mmm
I found code to undo a dictionary association.
def undict(dd, name_space=globals()):
for key, value in dd.items():
exec "%s = %s" % (key, repr(value)) in name_space
So if i run
I get1 B
Here, a=1 and b='B'
This works well enough for simple tasks and I understand the role of
globals() as the default names space, but creating local variables is
a problem. Also having no output arguemtns to undict() seems
counterintuitive. Also, the function fails if the key has spaces or
operand characters (-,$,/,%). Finally I know I will have cases where
not clearing (del(a,b)) each key-value pair might create problems in a
loop.
So I wonder if anyone has more elegant code to do the task that is
basically the opposite of creating a dictionary from a set of
globally assigned variables. And for that matter a way to create a
dictionary from a set of variables (local or global). Note I am not
simply doing and undoing dict(zip(keys,values))
def undict(dd, name_space=globals()):
for key, value in dd.items():
exec "%s = %s" % (key, repr(value)) in name_space
So if i run
I get1 B
Here, a=1 and b='B'
This works well enough for simple tasks and I understand the role of
globals() as the default names space, but creating local variables is
a problem. Also having no output arguemtns to undict() seems
counterintuitive. Also, the function fails if the key has spaces or
operand characters (-,$,/,%). Finally I know I will have cases where
not clearing (del(a,b)) each key-value pair might create problems in a
loop.
So I wonder if anyone has more elegant code to do the task that is
basically the opposite of creating a dictionary from a set of
globally assigned variables. And for that matter a way to create a
dictionary from a set of variables (local or global). Note I am not
simply doing and undoing dict(zip(keys,values))