NameError when assigning dictionary values

zsoltman at my-deja.com zsoltman at my-deja.com
Sun Apr 2 19:07:04 EDT 2000


If I am not mistaken, you are trying create two new list variables on
the fly (If I'm wrong, you can ignore the rest).  If this is what you
are trying to do, you need to use the exec and eval functions.  Below
is an example.
Let me warn though, you must be vigilant with your error trapping.
These functions can end up causing you a major headache otherwise.
(Notice I threw the invalid variable name '^' to show how confusing
this can get)

print
listVariables=['one','^','two','three']
for eachVariable in listVariables:
  execString=eachVariable+'= []'
  try:
    print 'Running statement '+execString
    exec(execString)
  except:
    print 'Something went wrong trying to execute the
statement "'+execString+'"'

print 'one   = ',one
print 'two   = ',two
print 'three = ',three

# to dynamically get these values
print 'Now getting dynamically'
for eachVariable in listVariables:
  try:
   print eachVariable+'   =',eval(eachVariable)
  except:
    print 'Something went wrong trying to evaluate variable
named "'+eachVariable+'"'





In article <20000402220351.9903.qmail at web2103.mail.yahoo.com>,
lewst <lewst at yahoo.com> wrote:
> Gordon McMillan <gmcm at hypernet.com> wrote:
>
> > > # 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?
> >
> > You're creating two empty lists, both named "value".The first
> > is thown away by creating the second. Nowhere are "one" and
> > "two" variable names, hence the NameError.
>
> Ok. So now how do I get the program to do what I want?
>
> __________________________________________________
> Do You Yahoo!?
> Talk to your friends online with Yahoo! Messenger.
> http://im.yahoo.com
>
>


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list