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

Hey there! Today we are going to cover the various techniques or methods to check if a given key exists in a Python Dictionary or not.

嘿! 今天,我们将讨论各种技术或方法,以检查给定密钥是否在Python字典中存在

介绍 (Introduction)

In many cases, we may need to check the presence of a key in a dictionary before adding, accessing, or modifying one to avoid an error. For that before-hand checking, we can follow any one of the below-mentioned methods.

在许多情况下,我们可能需要在添加,访问或修改一个字典之前检查字典中某个键的存在,以避免出现错误。 对于该事前检查,我们可以采用以下任何一种方法。

So without further ado, let us get started.

因此,事不宜迟,让我们开始吧。

检查密钥是否存在的方法 (Ways to check if a key exists)

Below, we have mentioned the five(5) of the most common and easy techniques for accomplishing the task.

下面,我们提到了完成任务的最常见和最简单的五(5)种技术。

  1. Using try-except code Block,

    使用try-except代码块,
  2. the ‘in’ operator,

    “ in”运算符
  3. the get() Method,

    get()方法,
  4. keys() Method,

    keys()方法,
  5. the has_key() Method.

    has_key()方法。

Now, we are going to go through each one of them one-by-one.

现在,我们将逐一逐一介绍它们。

1.使用try-except代码块 (1. Using try-except code Block)

A KeyError is raised when a key we are accessing doesn’t belong to the set of existing keys of the dictionary. We can use this fact to check for error(using exception handling) for checking if a key already exists in a dictionary.

当我们正在访问的键不属于字典中现有键的集合时,会引发KeyError 。 我们可以使用这个事实来检查错误(使用异常处理 ),以检查字典中是否已经存在键。

So in the below code example, we have used a try-except code block to try accessing our dictionary element with the given key. If the key exists, no exception will be raised and the else part would be executed. Whereas if a KeyError is encountered we can clearly infer that the key does not exist.

因此,在下面的代码示例中,我们使用了try-except代码块来尝试使用给定的键访问字典元素。 如果键存在,则不会引发异常,其他部分将被执行。 而如果遇到KeyError ,我们可以清楚地推断出该键不存在。


#Dictionary Initialisation
My_Dict = {'Joy':78, 'John':96, 'Kyler':65, 'Sona':85}

My_key = input("Enter the key to be searched: ")

try:
    My_Dict[My_key]
except KeyError:
    print("Key doesn't exist!")
else:
    print("Key present!")

Output:

输出:


Enter the key to be searched: Kyler
Key present!

Here since 'Kyler' is a key that already exists in the dictionary My_Dict, KeyError is not raised. And hence, we get our desired output.

在这里,因为'Kyler'是已经存在在字典中的一个关键My_Dict ,KeyError异常不提高。 因此,我们得到了期望的输出。

2.使用“ in”运算符 (2. Using ‘in’ operator)

The Python in operator is used for checking whether an element is present in a sequence or not. The syntax for using the same is given below.

Python in运算符用于检查元素是否按顺序存在。 下面给出了使用相同语法的语法。


given_key in given_dictionary

Here, the above code snippet evaluates to True if given_key is present in the sequence(for this article dictionary) given_dictionary. Or else to False if it is not.

在这里,如果在序列(对于本文字典) given_dictionary存在given_key ,则上述代码段的评估结果为True 。 如果不是,则为False

Have a look at the example given below. It illustrates the use of the in operator on a dictionary perfectly.

看下面的例子。 它完美地说明了in运算符在字典上的用法。


#Dictionary Initialisation
My_Dict = {'Joy':78, 'John':96, 'Kyler':65, 'Sona':85}

My_key = input("Enter the key to be searched: ")

if My_key in My_Dict:
    print("Found!")
else:
    print("Not Found!")

Output:

输出:


Enter the key to be searched: Joy
Found!

3.使用get()方法 (3. Using get() Method)

The get() method in Python returns the value for the given key if it is in the dictionary on which the method is applied. If the key does not exist, the default set by the user is returned.

如果给定键在应用该方法的字典中,则Python中的get()方法将返回该键的值。 如果密钥不存在,则返回用户设置的默认值。


get(key[, default])

Here, key is the key name that we are searching for.

在这里, key是我们要搜索的密钥名称。

Look at the below-given code snippet carefully.

仔细查看下面给出的代码片段。


#Dictionary Initialisation
My_Dict = {'Joy':78, 'John':96, 'Kyler':65, 'Sona':85}

My_key = input("Enter the key to be searched: ")

if My_Dict.get(My_key):
    print("Found!")
else:
    print("Not Found!")

Output:

输出:


Enter the key to be searched: John
Found!

From the above output it is clear that "John" is already present in the dictionary My_Dict.

从上面的输出中可以清楚地看出, "John"已经存在于字典My_Dict

4.使用keys()方法 (4. Using keys() Method)

The Python dictionary keys() method returns a new view of the dictionary’s keys. Hence, we can use this method to check if a key exists in Python Dictionary by using a combination of this method and the in operator.

Python字典keys()方法返回字典keys()的新视图。 因此,可以结合使用此方法和in运算符来使用此方法检查Python词典中是否存在键。

Here is an example below for better understanding.

下面是一个示例,可以使您更好地理解。


#Dictionary Initialisation
My_Dict = {'Joy':78, 'John':96, 'Kyler':65, 'Sona':85}

My_key = input("Enter the key to be searched: ")

if My_key in My_Dict.keys():
    print("Found!")
else:
    print("Not Found!")

Output:

输出:


Enter the key to be searched: Sneh
Not Found!

Since, the given key in this case does not belong to the set of keys present inside the dictionary, we get a negative result.

由于在这种情况下给定的键不属于字典中存在的键集,因此得到的结果为负。

5.使用has_key()方法 (5. Using has_key() Method)

The has_key() method has been omitted in Python 3.x versions and hence can be only used in older versions.

has_key()方法在Python 3.x版本中已被省略,因此只能在旧版本中使用。

So for the older versions, we can use this method to check if a key exists in Python Dictionary. The method returns True if the passed key exists in the dictionary. Or else, returns False. Have a look at an example below.

因此,对于较旧的版本,我们可以使用此方法检查Python词典中是否存在密钥。 如果传递的键存在于字典中,则该方法返回True 。 否则,返回False 。 请看下面的例子。


#Dictionary Initialisation
My_Dict = {'Joy':78, 'John':96, 'Kyler':65, 'Sona':85}

My_key = "Sona"

print(My_Dict.has_key(My_key)) #bool result

if My_Dict.has_key(My_key):
    print("Found!")
else:
    print("Not Found!")

Output:

输出:


True
Found!

We can see here that the method returns a True since the given key(“Sona“) exists.

我们在这里可以看到,由于给定的键(“ Sona ”)存在,因此该方法返回True

加起来 (Summing Up)

That’s it for today. In this tutorial, we discussed the various methods of checking whether a given key exists in a dictionary or not. Hope you had a clear understanding.

今天就这样。 在本教程中,我们讨论了检查字典中是否存在给定键的各种方法。 希望您有一个清楚的了解。

We recommend going through our Python tutorial for more info.

我们建议您阅读我们的Python教程以获取更多信息。

For any further questions, feel free to use the comments below.

如有其他疑问,请随时使用以下评论。

参考资料 (References)

翻译自: https://www.journaldev.com/40231/check-if-a-key-exists-in-python-dictionary

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值