[Tutorial] Replacing multiple (el)ifs with one dictionary access

Terry Reedy tjreedy at udel.edu
Wed Jan 24 15:16:10 EST 2001


[Tutorial posting for Python beginners]

In a nice response to a question by Oliver Vecernik <vecernik at aon.at> ,
Emile van Sebille <emile at fenx.com>  included the following code,
which is similar to other snippets occasionally posted to comp.lang.python.

if REQUEST.printLoc == "California":
  printerID = r"\\nova104\weber"
  printerDevice = "LPT2"
  outFile = r'f:\CA_Label.txt'
  batFile = r'f:\CA_Label.cmd'
 elif REQUEST.printLoc == "Illinois":
  printerID = r"\\shipping\webera1"
  printerDevice = "LPT3"
  outFile = r'f:\IL_Label.txt'
  batFile = r'f:\IL_Label.cmd'
 elif REQUEST.printLoc == "None":
  printerID = r"\\fclt\weber"
  printerDevice = "LPT2"
  outFile = r'f:\FX_Test.txt'
  batFile = r'f:\FX_Test.cmd'

Such multiple-if  switches with redundant parallel bodies look like literal
translations into Python of code or thought-forms based on other languages
that lack some of Python's features.  They can often be replaced with one
Python dictionary access.  The condensed code below makes the parellelism
clearer and easier to extend to additional printLocs

PrintDict = {   #printerID,          printerDevice,  outFile,
BatFile
  "California": (r"\\nova104\weber",    "LPT2",  r'f:\CA_Label.txt',
r'f:\CA_Label.cmd'),
  "Illinois":      (r\\shipping\webera1",  "LPT3",  r'f:\IL_Label.txt',
r'f:\IL_Label.cmd'),
  "None":         (r"\\fclt\weber",            "LPT2",  r'f:\FX_Test.txt'.
r'f:\FX_Test.cmd')
  }
printerID, printerDevice, outFile, batFile = PrintDict[REQUEST.printLoc]

This version uses two Python features, dictionary access and tuple
unpacking, that have no direct equivalent in many of the languages that
people learn before Python.  They are therefore easy to sometimes
underutilize.  In particular, the 'proper' Pythonic equivalent of a case or
switch statement in other languages is often a dictionary access rather
than a series of if/elif blocks.

Terry J. Reedy   tjreedy at udel.edu








More information about the Python-list mailing list