将 "if..elif..else" 语句转换为字典查找时如何处理 "else" 子句?

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

我正在尝试将 python 中的 "if else" 语句转换成字典。

我试图将其转换为字典,但如何处理最后一个 else 子句?

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]

我创建了此代码作为替代:

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

是否等价?

您可以使用dict.get方法:

print DATA_SOURCE.get(val, "value not found")

如果 val 不是键,那么 return "value not found" 不会影响字典。

一如既往,如有疑问,请使用帮助:

>>> help(dict)

我想你正在寻找;

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