NameError when assigning dictionary values

Fredrik Lundh effbot at
Sun Apr 2 23:40:15 CEST 2000

lewst <lewst at> wrote:
> This simple problem is driving my crazy.  I can't figure out why I get
> a NameError with this program.
>   # add each key-value pair to the dictionary and
>   # then for each value, create an empty list.
>   mydict = {}
>   for key,value in [ (".", "one"), ("+", "two") ]:
>       mydict[key] = value
>       value = []
>   print mydict
>   print one,two
> Whe I run this I get "NameError: one".  Why aren't my 2 empty lists
> named "one" and "two" being created?

I haven't the foggiest idea of what you expect Python
to do here (or why you expect it to work in that way),
but let's step through your code by hand:

>   mydict = {}

this creates an empty dictionary, named 'mydict'.

>   for key,value in [ (".", "one"), ("+", "two") ]:

this loops over a list, containing two 2-tuples.
the first time, it sets 'key' to ".", and 'value' to
"one".  the second time, it sets 'key' to "+" and
'value' to "two".

>       mydict[key] = value

this adds a member to the dictionary, with the
key "." and value "one"

>       value = []

this creates a new empty list, and changes 'value'
to point to the list instead of the original value.

not that it matters much -- the second time through
the loop, 'value' will be set to "two" by the for-in state-

>   print mydict

this prints the contents of the dictionary (which, in
this case, is something like {"+": "two", ".": "one"} )

>   print one,two

this attempts to print the variables 'one' and 'two.

there are no such variables -- you haven't assigned
them.  that's why

there are two *keys* in the dictionary, but that's a
completely different thing.  dictionaries are container
objects.  putting things is a dictionary doesn't make
it visible in the variable namespace.

I suggest reading the tutorial over again, and perhaps
signing up to the tutor mailing list.  you'll find pointers


More information about the Python-list mailing list