[Tutor] replacing a long list of if,elif
John
jfabiani at yolo.com
Fri Oct 23 17:58:43 CEST 2009
On Friday 23 October 2009 08:05:29 am John 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
>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
Thanks this looks perfect - did not know dict.get()
Johnf
Vince
More information about the Tutor
mailing list