"Extracting" a dictionary

xtian xtian at toysinabag.com
Mon May 17 20:49:09 EDT 2004


Daniel Klein <bringa at gmx.at> wrote in message news:<mailman.20.1084820319.6949.python-list at python.org>...
> Is there a way to 'extract' a dictionary into the current namespace? 
> That is, if you have
> {'foo' : 23, 'bar' : 42}
> you would get a variable foo with value 23 and a variable bar with value 
> 42? Such a function would of course only work on string keys and would 
> probably have to check that, but still, it sounds practical enough that 
> surely someone else thought of it before.
> 
> Daniel

The most straightforward way I know is

>>> d = {'foo': 23, 'bar': 42}
>>> globals().update(d)
>>> print foo, bar
23 42

This only works with globals, though - there's a corresponding
locals(), but unfortunately the docs say updating it's a no-no - the
dict returned could be a copy of the real locals dict (or the real
locals might not be in a dict at all). The interpreter is free to
ignore changes to the dictionary that locals() returns (although it
happens not to in CPython at the moment, that's an implementation
detail).

Even with the globals, it's a bit magical and could end up overwriting
names that match a key in the dictionary (it would be irritating if
one of the keys was "file" or "list").

Maybe a cleaner way to do essentially what you want is to use the
martellibot's Bunch recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308

This would allow you to do:

>>> class Bunch:
    def __init__(self, **kwds):
        self.__dict__.update(kwds)

        
>>> d = {'foo': 23, 'bar': 42}
>>> bunch = Bunch(**d)
>>> print bunch.foo, bunch.bar
23 42

This means you're not clobbering the global or local namespace with
arbitrary bindings, and you could have lots of Bunch instances for
different collections of bindings.

Cheers,
xtian



More information about the Python-list mailing list