Python中如何检查一个键在字典中是否存在

by LauCyun Sep 10,2016 17:02:25 4,695 views

在更新字典之前想检查键是否存在。我写了如下代码:

if 'key1' in dict.keys():
  print "blah"
else:
  print "boo"

我想这不是最好的方法,还有什么更好的方法?

in

>>> dict = {"a": 1, "b": 2, "c": 3, "d": 4}
>>> if "a" in dict:
...     print("YES");
... else:
...     print("NO");
...
YES
>>> if "d" in dict:
...     print("YES");
... else:
...     print("NO");
...
YES
>>> if "g" in dict:
...     print("YES");
... else:
...     print("NO");
...
NO
>>>

如果你想要获取属性只,你可以用dict.get()

>>> dict = {"a": 1, "b": 2, "c": 3, "d": 4}
>>> dict.get("a")
1
>>> dict.get("g")
>>>

所以,in是最好的方法。

Tags