在我的Ruby应用程序中,我有一个哈希表:
c = {:sample => 1,:another => 2}
我可以像这样处理表格:
[c[:sample].nil? , c[:another].nil? ,c[:not_in_list].nil?]
我正在尝试用Python做同样的事情。我创建了一个新词典:
c = {"sample":1, "another":2}
我无法处理:
的nil值异常c["not-in-dictionary"]
我试过了:
c[:not_in_dictionery] is not None
并且它返回一个异常而不是False.
我该如何处理?
答案 0 :(得分:33)
在您的特定情况下,您应该这样做,而不是与None
进行比较:
"not_in_dictionary" in c
如果您确实使用此代码,则无效:
c[:not_in_dictionary] is not None
Python对字典键没有特殊的:
关键字;改为使用普通的字符串。
Python中的普通行为是在请求丢失密钥时引发异常,并允许您处理异常。
d = {"a": 2, "c": 3}
try:
print d["b"]
except KeyError:
print "There is no b in our dict!"
如果您希望获得None
,如果缺少值,您可以使用dict
的{{1}}方法返回值(默认情况下为.get
)钥匙不见了。
None
要检查某个密钥是否具有print d.get("a") # prints 2
print d.get("b") # prints None
print d.get("b", 0) # prints 0
中的值,请使用dict
或in
个关键字。
not in
Python包含一个模块,允许您定义在正常使用时返回默认值而不是错误的字典:collections.defaultdict
。您可以像这样使用它:
print "a" in d # True
print "b" in d # False
print "c" not in d # False
print "d" not in d # True
请注意import collections
d = collections.defaultdict(lambda: None)
print "b" in d # False
print d["b"] # None
print d["b"] == None # True
print "b" in d # True
的混淆行为。当您第一次查找某个键时,它会将其添加为指向默认值,因此它现在被视为in
in
。