NameError when assigning dictionary values

Fredrik Lundh effbot at telia.com
Mon Apr 3 01:44:23 CEST 2000


lewst <lewst at yahoo.com> wrote:
> I was trying to build a dictionary and create lists corresponding to
> the value names in the dictionary in one loop.

unlike Tcl, you don't need to create *variables* to be
able to store *values* to your dictionary.

> Do I really have to type "one" and "two" twice?  Once to make it a
> variable and a second time to add to my dictionary?  I.e,

no.  reset your brain.  forget about variables.  just put
new *values* (aka objects) in the dictionary.

> This seems error prone if the the number of variables grows very large
> as it will for me.

let me guess: what you really want to do is to have a
number of lists, each of which are identified by a string?

    mydict = {}
    for k in ("one", "two"):
        mydict[k] = []

and then you want to update one of them:

    mydict["one"].append("1")

and then you want to print them all:

    for k, v in mydict.items():
        print k, v

did I successfully read your mind this time?

</F>

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list