Want to add dictionary keys to namespace?

Chris Angelico rosuav at gmail.com
Fri Nov 9 19:52:39 EST 2012


On Sat, Nov 10, 2012 at 11:00 AM, Jeff Jeffries
<jeff.jeffries.iii at gmail.com> wrote:
> Smart people, Is there a way I can add a dictionaries keys to the python
> namespace? It would just be temporary as I am working with a large
> dictionary, and it would speed up work using an IDE.  I look and find
> nothing... none of the keys have spaces and none are common names within the
> module.
>
> #Do this?
> dictionary = {"AppleSeed": None, "Has": None,"Horrible" :None,"Art"}
> for key in dictionary.keys():
>      eval("%s=None"%key)

I would strongly recommend not.

> #or do this?
> locals().update(dictionary)

That doesn't work in a function, but outside of a function, you should
be able to use:

globals().update(dictionary)

However, I would advise using the dictionary explicitly. Give it a
shorter name and it'll be easier, but don't go for namespace
pollution. The PHP folks finally realized that register_globals is a
bad idea.

ChrisA



More information about the Python-list mailing list