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

标签 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: "something",
       5: "something", 11: "something", 8: "something", 10: "something"}

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

问题是如果i等于3,那么它会检查arr[3*2]是否会返回一些东西,它不会' t 因为没有键 6,所以会返回错误。

我怎样才能用我的想法做到这一点?

最佳答案

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

<小时/>

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

if i * 2 in dict_object:
    print "!"

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

<小时/>

还有一种方法可以做到这一点。字典对象有一个名为 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]

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

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

关于python - 如何查找字典中是否存在键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30175217/

相关文章:

python - Docker、python3 yaml.safe_load()读取中文文件无法工作

python - easy_install 在 Mac 上损坏

python - 为什么 somelist[len(somelist)] 生成一个 IndexError 而不是 somelist[len(somelist) :]?

python - 使用pip安装python包报错

python - 我如何告诉 OSX 使用brew 中的matplotlib,而不是默认的?

python - 连接不同列表中的两个字符串

python - 视频捕获窗口未关闭 - OpenCV

string - Haskell 输入创建字符串列表

python - 为什么 append 方法在我的列表中返回 None?

Python 比较列表平均值排序