"Extracting" a dictionary

Peter Hansen peter at engcorp.com
Tue May 18 08:55:19 EDT 2004


Jason Mobarak wrote:

> Is this illegal?
> 
>  >>> import __main__
>  >>> d = {'foo':'oof','bar':'rab','baz':'zab'}
>  >>> for k,v in d.items():
> ...   setattr(__main__, k, v)
> ...
>  >>> foo,bar,baz
> ('oof', 'rab', 'zab')

It executes, apparently, so why would you think it was "illegal"?

Note, however, that attempts to create variables programmatically
like this are almost always ill-conceived.  If you don't know the
name of the variable in the first place, how are you planning to
access it later?  And, as someone already said, it's probably better
just to continue to access things in the dictionary.  More readable
probably.

-Peter



More information about the Python-list mailing list