undo a dictionary
Kay Schluehr
kay.schluehr at gmx.net
Wed Jul 30 11:22:56 EDT 2008
On 30 Jul., 16:51, mmm <mdbol... at gmail.com> 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
>
> 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.
Python is lexically scoped. You can't create locals at runtime.
> Also having no output arguemtns to undict() seems
> counterintuitive. Also, the function fails if the key has spaces or
> operand characters (-,$,/,%).
Python names can't have punctuation with the exception of underscores.
> 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))
May I ask what's wrong with having namespaces in a language?
More information about the Python-list
mailing list