'for' loop in python, error: unsubscriptable object

John Hunter jdhunter at ace.bsd.uchicago.edu
Mon Nov 18 10:41:30 EST 2002


This is the kind of task a dictionary is made for:

mydict = {CLA : " the Clangers",
          RBW : "Rainbow",
          BAG : "Bagpuss",
          MRB : "Mr Benn",
          NOG : "Noggin the Nog"}
  
name = []
somelist = [CLA, RBW, BAG, MRB, NOG]
for key in somelist:
    name.append( mydict[key] )

Anytime you are tempted to write a bunch of if/elif statements, think
about doing it with a dictionary.  A dictionary in python can handles
most if/elif and case/switch scenarios.  You can map cases to
arbitrary functions with a dictionary, which makes them quite useful

def func1():
    print " the Clangers"
    
def func2():
    print "Rainbow"
    
def func3():
    print "Bagpuss"
    
def func4():
    print "Mr Benn"
    
def func5():
    print "Noggin the Nog"

mydict = {CLA : func1,
          RBW : func2,
          BAG : func3,
          MRB : func4,
          NOG : func5}
  
for key in somelist:
    func = mydict[key]
    func()



You can use the get method of dictionaries to provide default
behavior, such as a function to call when no key matches

def default_func():
    print "What the hell is that?"

for key in somelist:
    func = mydict.get(key, default_func)
    func()

And so on.  Dictionaries are fun (and they're good for you too!)

PS:

for max in range[CLA, RBW, BAG, MRB, NOG]:
    ^ don't use max as a variable name it's a builtin function


John Hunter




More information about the Python-list mailing list