I am trying to remove if else from python. One option is to convert it into dictionary. But now problem is for last else part.
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 found below option. Can someone suggest whether it is correct .
if not DATA_SOURCE.has_key(val):
print "value not found:"
else:
print DATA_SOURCE[val]
I have seen setdefault option somewhere but could not understand. Please someone suggest me proper option.
Aucun commentaire:
Enregistrer un commentaire