undo a dictionary

mmm mdboldin at gmail.com
Wed Jul 30 10:51:43 EDT 2008


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

>>> dx= { 'a':1, 'b': 'B'}
>>> undict(dx)

I get
>>> print A, B
1 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))



More information about the Python-list mailing list