[Tutor] replacing a long list of if,elif

vince spicer vinces1979 at gmail.com
Fri Oct 23 17:18:09 CEST 2009


On Fri, Oct 23, 2009 at 9:05 AM, John <jfabiani at yolo.com> wrote:

> 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
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

John,

Using a Dictionary is the best method to use here and you can use dict.get
in order to bypass the KeyError

EX:

myDict.get(fldType, None)

this will output the value from myDict if the key exists, if not it will
return None


Vince
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091023/2051aa59/attachment.htm>


More information about the Tutor mailing list