On Fri, Oct 23, 2009 at 9:05 AM, John <jfabi...@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@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
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor