undo a dictionary
Terry Reedy
tjreedy at udel.edu
Wed Jul 30 13:22:51 EDT 2008
mmm wrote:
> 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
You are not undoing anything. You are updating globals() from another
dict. But why repr(value)? Without that, globals().update(dd) would
work. In 2.6?/3.0, replace 'dd' with '{a:b for a,b in dd.items()}
dd = { 'a':1, 'b': 'B'}
globals().update({a:b for a,b in dd.items()})
print(a,b)
# 1,B
>>>> dx= { 'a':1, 'b': 'B'}
>>>> undict(dx)
>
> I get
>>>> print A, B
> 1 B
>
> Here, a=1 and b='B'
Don't fake interactive output. You would have to "print a,b". Above
gives a NameError.
> 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.
Within functions, yes. Just access the values in the dict.
> Also having no output arguemtns to undict() seems
> counterintuitive.
In Python, this is standard for functions that mutate.
> Also, the function fails if the key has spaces or
> operand characters (-,$,/,%).
Exec is tricky. Most people hardly ever use it.
> Finally I know I will have cases where
> not clearing (del(a,b)) each key-value pair might create problems in a
> loop.
You cannot mutate a dict while iterating through it.
> 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.
See above.
> And for that matter a way to create a
> dictionary from a set of variables (local or global).
You have to be more specific: there are {} displays and dict(args) call
and other methods. Read the manual.
tjr
More information about the Python-list
mailing list