Dictionary vs if-elif?
Wolfgang Grafen
Wolfgang.Grafen at marconicomms.com
Wed Jun 21 08:44:06 EDT 2000
William Dandreta wrote:
> Here is a code snippet
> -------------------------------------------------------------------------
> bogusCodes = { '1.':'', '31':'', '90':'', 'AZ':'', 'BH':'', 'C1':'',
> 'CB':'', 'FR':'', 'HD':'', 'JF':'', 'KL':'', 'KU':'',
> 'LU':'', 'ON':'', 'PF':'', 'Q3':'', 'UP':'', 'W4':'',
> 'WO':''}
>
> item = data.readline()
> while item:
> if (item[1:2] in digits) and (item[0:1] == 'D'):
> goodVend.write(item)
> elif vendors.has_key(item[0:2]):
> goodVend.write(item)
> elif bogusCodes.has_key(item[0:2]):
> pass
> else:
> missingVend.write('Vendor code %s is missing from file VendCode.txt\n' %
> item[0:2])
> item = data.readline()
> ---------------------------------------------------------------
> originally I had it written like so:
>
> if ...:
> pass
> elif...:
> pass
> etc.
> -------------------------
> another possibility is and if statement with a very complex condition:
> if a or b or c ...:
> pass
> else :
> etc
> ---------------------
> Is there a better way to do it?
> Which of these three would be the preferred method?
>
> Bill
Hi Bill,
try a very fast version:
bogusCodes = ['1.', '31', '90', 'AZ', 'BH', 'C1',
'CB', 'FR', 'HD', 'JF', 'KL', 'KU',
'LU', 'ON', 'PF', 'Q3', 'UP', 'W4',
'WO']
DDIGITS = map(lambda x:'D%s'%x,range(10)
vendorCodes = ['2.','41'] # as an example
def PASS(key):
pass
dict = {}
for key in bogusCodes:
dict[key] = PASS
for key in vendorCodes + DDIGITS:
dict[key] = goodVend.write
while 1:
item = data.readline()
try:
key = item[:2]
dict[key](item)
except KeyError:
missingVend.write(
'Vendor code %s is missing from file VendCode.txt\n'%item[0:2])
Wolfgang
More information about the Python-list
mailing list