"Extracting" a dictionary

Heiko Wundram heikowu at ceosg.de
Mon May 17 15:10:51 EDT 2004


Am Montag, 17. Mai 2004 20:58 schrieb Daniel Klein:
> 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.

There is no way to do what you're asking. The local variables dictionary 
(which exists and is accessible using locals()) should never be modified, and 
besides, I think that it is plain ugly programming if you insert unknown 
variables (you don't actually know what data is in the dictionary, do you? If 
you do, why would you want to insert it, and not access it using the 
dictionary keys?) into the local namespace.

But, as always in Python ;), there is a way to do this which is cleaner (IMHO) 
and mimicks what you're asking for:

def f(foo=None,bar=None):
	print "I got foo:", foo
	print "I got bar:", bar

dct = {"foo":23,"bar":42}
dct2 = {"bar":42}

f(**{"foo":23,"bar":42})
f(**dct)
f(**dct2)

If that isn't enough, go check on the eval directive in the documentation, 
which allows you to specify a local namespace (a dictionary object) for the 
code (object) that is executed.

HTH!

Heiko.




More information about the Python-list mailing list