>>> temp = {}
>>> help(temp.__contains__)
Help on built-in function __contains__:
__contains__(key, /) method of builtins.dict instance
True if D has a key k, else False.
try:
my_dict_of_items[key_i_want_to_check]
except KeyError:
# Do the operation you wanted to do for "key not present in dict".
else:
# Do the operation you wanted to do with "key present in dict."
# suppose your dictionary is
my_dict = {'foo': 1, 'bar': 2}
# check if a key is there
if 'key' in my_dict.keys(): # it will evaluates to true if that key is present otherwise false.
# do something
或者你也可以简单地做:
if 'key' in my_dict: # it will evaluates to true if that key is present otherwise false.
# do something
在旧代码中,您可能还会发现 has_key() 的一些用法,这是一种不推荐使用的方法,用于检查字典中是否存在键(仅使用 key_name in dict_name ) .
42
print dict.get('key1', 'blah')
不会为dict中的值打印boo,而是通过打印key1的值来确认它的存在来实现目标 .
0
我建议改用 setdefault 方法 . 听起来它会做你想要的一切 .
>>> d = {'foo':'bar'}
>>> q = d.setdefault('foo','baz') #Do not override the existing key
>>> print q #The value takes what was originally in the dictionary
bar
>>> print d
{'foo': 'bar'}
>>> r = d.setdefault('baz',18) #baz was never in the dictionary
>>> print r #Now r has the value supplied above
18
>>> print d #The dictionary's been updated
{'foo': 'bar', 'baz': 18}
0
You can use the has_key() method:
if dict.has_key('xyz')==1:
#update the value for the key
else:
pass
Or the dict.get method to set a default value if not found:
19 回答
只是一个FYI加入克里斯 . B(最佳答案):
也适用;原因是调用
int()
返回0
这是幕后的defaultdict
(构建字典时),因此文档中的名称为"Factory Function" .要检查,您可以使用
has_key()
方法如果你想要一个值,那么你可以使用
get()
方法如果你想要一个元组或列表或字典或任何字符串作为默认值作为返回值,那么使用
get()
方法有关接受答案的建议方法(10米循环)的速度执行的其他信息:
'key' in mydict
经过时间1.07秒mydict.get('key')
经过时间1.84秒mydefaultdict['key']
经过时间1.07秒因此,建议对
get
使用in
或defaultdict
.我用的是try / except;如果抛出异常,则字典中不存在密钥 . 例:
python中的字典有一个get('key',default)方法 . 所以你可以设置一个默认值,以防没有密钥 .
Python字典有一个名为
__contains__
的方法 . 如果字典具有键,则此方法将返回True,否则返回False .The ways in which you can get the results are:
if your_dict.has_key(key)Removed in Python 3
如果在your_dict中输入密钥
尝试/除块
Which is better is dependent on 3 things:
字典是'normally has the key'还是'normally does not have the key' .
你是否打算使用if ...... else ... elseif ...... else等条件?
字典有多大?
阅读更多:http://paltman.com/try-except-performance-in-python-a-simple-test/
使用try / block代替'in'或'if':
你可以缩短这个:
然而,这充其量只是一种美容改善 . 为什么你认为这不是最好的方法?
您不必调用密钥:
这将是faster,因为它使用字典的散列而不是进行线性搜索,调用键会这样做 .
如果您知道要查找哪个密钥(密钥名称),最简单的方法是:
或者你也可以简单地做:
嗯..你会很熟悉在列表或数据中搜索元素的存在意味着遍历所有内容(至少对于无序列表,例如dict.keys) . 因此,使用通常出现的异常和错误,我们可以避免这种复杂性......
如何使用EAFP(更容易请求宽恕而非许可):
查看其他SO帖子:
Using try vs if in python或
Checking for member existence in Python
您可以使用 in 关键字测试字典中是否存在密钥:
在变更之前检查字典中是否存在键的常见用法是默认初始化值(例如,如果您的值是列表,并且您希望确保有一个空列表,您可以将其追加到插入键的第一个值时) . 在这种情况下,您可能会发现collections.defaultdict()类型是有意义的 .
在旧代码中,您可能还会发现
has_key()
的一些用法,这是一种不推荐使用的方法,用于检查字典中是否存在键(仅使用key_name in dict_name
) .print dict.get('key1', 'blah')
不会为dict中的值打印boo,而是通过打印key1的值来确认它的存在来实现目标 .
我建议改用
setdefault
方法 . 听起来它会做你想要的一切 .You can use the has_key() method:
Or the dict.get method to set a default value if not found:
in
是测试dict
中是否存在密钥的预期方法 .如果您想要默认值,可以始终使用
dict.get()
:...如果您想始终确保任何键的默认值,您可以使用
collections
模块中的defaultdict
,如下所示:...但一般来说,
in
关键字是最好的方法 .使用三元运算符:
为什么不使用has_key()方法 .