[Tutor] replacing a long list of if,elif

Kent Johnson kent37 at tds.net
Fri Oct 23 19:51:22 CEST 2009


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

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

Use
  fld = mydict.get(fldType, '?')

> I also considered some sort of  lambda function as
>
> x = lambda fld: mydict[fldType]

You don't have to use a lambda, you can use the dict methods, e.g.
  x = mydict.__getitem__
or
  x = mydict.get

> 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)

This is really no different than just using
  mydict[fldType]
directly.

> else:
>    fld = '?'

Kent


More information about the Tutor mailing list