On 30 Lug, 16:51, mmm <[EMAIL PROTECTED]> 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. 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))


Maybe you can use objects as pseudo name spaces and do sommething like
this:

>>> class Scope(object):
        def dict(self):
                res = dict()
                for k, v in self.__dict__.items(): res[k] = v
                return res
        def undict(self, dict):
                for k,v in dict.items():
                        setattr(self, k, v )


>>> myscope = Scope()
>>> myscope.undict(dict(A=1, B=2))
>>> myscope.A
1
>>> myscope.B
2
>>> myscope.dict()
{'A': 1, 'B': 2}
>>>


Ciao
------
FB


--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to