pythonif-statementtechnical-debt

How to handle the "else" clause when converting an "if..elif..else" statement into a dictionary lookup?


I am trying to convert an "if else" statement in python into a dictionary.

I tried to convert it into a dictionary, but how do I handle the last else clause?

val=3

if val==1:
  print "a"
elif val==2:
  print "b"
elif val==3:
  print "c"
elif val==4:
  print "d"
else:
  print "value not found:"

print "===========Converted if else into dictionary ==================="

DATA_SOURCE = {1:"a",2:"b",3:"c",4:"d"}
print DATA_SOURCE[val]

I have created this code as a replacement:

if not DATA_SOURCE.has_key(val):
  print "value not found:"
else:
  print DATA_SOURCE[val]

Is it equivalent?


Solution

  • I think you are looking for;

    val = 3
    dct = {1:"a", 2:"b", 3:"c", 4:"d"}
    if dct.get(val) == None: print "Value Not Found"