[Tutor] replacing a long list of if,elif

John jfabiani at yolo.com
Fri Oct 23 17:05:29 CEST 2009


I'm using python 2.5

I have a long list of if, elif, else.  I always thought it was very NOT 
pythonic.  It's easy to read but not pretty.

for fldType in fieldList:
  if "int" in fldType:
      fld = "I"
  elif "char" in fldType :
      fld = "C"
  elif "bool" in fldType :
     fld = "B" .....
  else:
     fld = '?'


I have considered:

  mydict = {'int': 'I', 'char':'C', 'bool':'B'....}
  for fldType in fieldList:
    try:
        fld = mydict[fldType]
    except:
        fld = '?'

I also considered some sort of  lambda function as 

x = lambda fld: mydict[fldType] 

But could not determine how to account for the key exception. So I tried

x = lambda fldType: mydict[fldType] 
if fldType in mydict:
   x(fldType)
else:
    fld = '?'


Any suggestions would be helpful  and would help me learn.

Johnf
   





More information about the Tutor mailing list