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

Python 如何查找字典中是否存在密钥?,python,list,python-2.7,dictionary,Python,List,Python 2.7,Dictionary,我想用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: "so

我想用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中,您称之为
arr
的项实际上被称为
list
。“哈希表”实际上被称为字典。因此,我将把
arr
对象称为
dict\u对象


您可以使用操作符中的
检查该键是否在字典中

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


还有一种方法可以做到这一点。dictionary对象有一个名为的函数,该函数接受在dictionary中找不到键时返回的默认值。默认返回值为
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 "!"
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
numbers_set = {1, 14, 2, 4, 5, 11, 8, 10}    # Note {..}, not [..]
if i * 2 in numbers_set:
    print "!"
numbers_set = set([1, 14, 2, 4, 5, 11, 8, 10])
if i * 2 in numbers_set:
    print "!"
for i in range(1, len(x) + 1):

还有另一种方法可以做到这一点。当您访问字典中不存在的密钥时,您将得到
KeyError
。除此之外,你可以这样做

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 "!"
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
numbers_set = {1, 14, 2, 4, 5, 11, 8, 10}    # Note {..}, not [..]
if i * 2 in numbers_set:
    print "!"
numbers_set = set([1, 14, 2, 4, 5, 11, 8, 10])
if i * 2 in numbers_set:
    print "!"
for i in range(1, len(x) + 1):

除此之外,如果没有使用您存储在字典中的值(换句话说,如果您只担心键),那么您可以使用set而不是字典,如下所示

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 "!"
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
numbers_set = {1, 14, 2, 4, 5, 11, 8, 10}    # Note {..}, not [..]
if i * 2 in numbers_set:
    print "!"
numbers_set = set([1, 14, 2, 4, 5, 11, 8, 10])
if i * 2 in numbers_set:
    print "!"
for i in range(1, len(x) + 1):
如果您已经有了列表,那么您可以使用函数将列表转换为集合,如下所示

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 "!"
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
numbers_set = {1, 14, 2, 4, 5, 11, 8, 10}    # Note {..}, not [..]
if i * 2 in numbers_set:
    print "!"
numbers_set = set([1, 14, 2, 4, 5, 11, 8, 10])
if i * 2 in numbers_set:
    print "!"
for i in range(1, len(x) + 1):

PS:您的程序中有一个bug。在Python中,
range
函数从第一个参数运行到最后一个参数值-1。比如说,

>>> range(1, 5)
[1, 2, 3, 4]
>>> range(2, 10)
[2, 3, 4, 5, 6, 7, 8, 9]
最后一个值将不包括在内。因此,您需要像这样更改
范围的参数

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 "!"
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
numbers_set = {1, 14, 2, 4, 5, 11, 8, 10}    # Note {..}, not [..]
if i * 2 in numbers_set:
    print "!"
numbers_set = set([1, 14, 2, 4, 5, 11, 8, 10])
if i * 2 in numbers_set:
    print "!"
for i in range(1, len(x) + 1):

老实说,我不明白你打算做什么,但你有一些选择

对于您的
arr
字典(哈希表)

arr.keys()
将返回
key
s

字典也有
get(key,message)
方法,如果此字典有这样的键,此方法将返回其值,否则
message
(默认
None

或者用按键打印,更清晰

>>> for i in range(len(arr)):
    print i, arr.get(i*2)


0 None
1 something
2 something
3 None
4 something
5 something
6 None
7 something
或仅为现有值打印消息

>>> for i in range(len(arr)):
    if i in arr.keys(): print arr.get(i*2)


something
something
something
something
或者这个

>>> for i in range(len(arr)):
    if i in arr.keys(): print i,"--->", arr.get(i*2)


1 ---> something
2 ---> something
4 ---> something
5 ---> something

您的问题实际上非常令人困惑,因为在第一个代码段中,您正在迭代列表的索引,而在第二个代码段中,您正在创建一个以列表元素为键的字典。此时不可能说出您真正想要什么,因此这里有一个答案,以防您确实想要检查索引
i*2
是否对任何有效的索引
i
有效

n = len(x)
y = [True]*sum(divmod(n, 2)) + [False]*(n//2)
此代码段可以高效地创建一个列表,并将其分配给
y
,该列表是从原始列表的每个有效索引
x
到一个布尔值的映射,该布尔值指示(
True
)或(
False
)索引
i*2
是否小于数组的长度

演示:


我认为字典的
get
方法就是你想要的


如果您执行
arr.get(2)
操作,它将返回您想要的值;如果没有值,它将返回
None

您可以使用get方法:arr.get(3*2,None)@DmytroKuznetsov默认值为
None
only:-),因此基本上您真正想做的是查看i*2是否小于列表的长度?我问你只是因为你的问题很奇怪。你不需要字典。