如何查找字典中是否存在密钥? - python

我想用python编写一个在列表中找到值的程序。
像这样:

arr = [1, 14, 2, 4, 5, 11, 8, 10]
for i in range(1, len(arr)):
    if(i * 2 in arr):
        print "!"

我要检查的数组要更长一些,因此需要很长时间。
我想出了一个制作哈希表而不是列表的想法。
像这样的东西:

arr = {1: "something", 14: "something", 2: "something", 4: "something",
       5: "something", 11: "something", 8: "something", 10: "something"}

我的想法是检查例如i是否等于2,以便检查arr[i*2]是否会返回某些内容,因为这样,程序就不需要查找某些东西就可以调用它(如果存在)。

问题是,如果i等于3,则它将检查arr[3*2]是否返回某些内容,不会,因为没有键6会返回错误。

我如何用我的想法做到这一点?

python大神给出的解决方案

注意:在Python中,您称为arr的项目实际上称为list。而“哈希表”实际上称为字典。因此,我将arr对象称为dict_object

您可以使用in运算符检查关键字是否在字典中,

if i * 2 in dict_object:
    print "!"

如果in是字典中的有效键,则True运算符将返回i * 2,否则返回False

还有另一种方法可以做到这一点。字典对象具有称为get的函数,如果在字典中未找到键,该函数将接受默认值。默认返回值为None。您可以使用None作为标记值,​​如下所示

if dict_object.get(i * 2) is not None:
    # If the returned value is not None, then the key is present in the dictionary
    print "!"

还有另一种方法可以做到这一点。当您访问词典中没有的键时,您将得到KeyError。您可以像这样

for i in range(1, len(dict_object) + 1):
    try:
        if dict_object[i * 2]:
            print "!"
    except KeyError:
         # If value of `i * 2` is not in the dictionary, we will reach here
         pass

除此之外,如果未使用存储在字典中的值(换句话说,如果您只担心键),则可以使用set而不是字典,例如

numbers_set = {1, 14, 2, 4, 5, 11, 8, 10}    # Note {..}, not [..]
if i * 2 in numbers_set:
    print "!"

如果已经有了列表,则可以使用set函数将列表转换为集合,如下所示

numbers_set = set([1, 14, 2, 4, 5, 11, 8, 10])
if i * 2 in numbers_set:
    print "!"

PS:您的程序中存在错误。在Python中,range函数从第一个参数开始运行,直到最后一个参数值-1。例如,

>>> range(1, 5)
[1, 2, 3, 4]
>>> range(2, 10)
[2, 3, 4, 5, 6, 7, 8, 9]

最后的值将不包括在内。因此,您需要像这样更改range的参数

for i in range(1, len(x) + 1):