检查key是否存在并在Python中同时获取值? [英] Check if key exists and get the value at the same time in Python?

查看:106
本文介绍了检查key是否存在并在Python中同时获取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时,我们可能需要验证字典中某个键的存在,并在相应值存在的情况下进行处理.

Sometimes we may need to verify the existence of a key in a dictionary and make something if the corresponding value exists.

通常,我以这种方式进行:

Usually, I proceed in this way:

if key in my_dict:
    value = my_dict[key]
    # Do something

这当然是高度可读和快捷的,但是从逻辑的角度来看,这使我感到困扰,因为同一动作连续执行两次.浪费时间.

This is of course highly readable and quick, but from a logical point of view, it bothers me because the same action is performed twice in succession. It's a waste of time.

当然,对字典中值的访问是摊销的,通常是瞬时的.但是,如果不是这种情况,并且我们需要重复多次,该怎么办?

Of course, access to the value in the dictionary is amortized and is normally instantaneous. But what if this is not the case, and that we need to repeat it many times?

我认为的第一个解决方法是使用.get()并检查返回的值是否不是默认值.

The first workaround I thought to was to use .get() and check if the returned value is not the default one.

value = my_dict.get(key, default=None)
if value is not None:
    # Do Something

不幸的是,这不是很实际,如果密钥存在并且其对应的值恰好是None,则会引起问题.

Unfortunately, this is not very practical and it can cause problems if the key exists and its corresponding value is precisely None.

另一种方法是使用try/except块.

Another approach would be to use a try / except block.

try:
    value = my_dict[key]
    # Do something
except KeyError:
    pass

但是,我高度怀疑这是最好的方法.

However, I highly doubt this is the best of ways.

还有其他我不知道的解决方案,还是应该继续使用传统方法?

Is there any other solution which is unknown to me, or should I continue using the traditional method?

推荐答案

如果缺少值的情况确实很特殊,则可以使用异常处理:

If the situations with missing values are really exceptional then the exception handling is appropriate:

try:
    value = my_dict[key]
    # Do something
except KeyError:
    pass

如果要同时处理丢失和出现的密钥,则您的第一个选择将很有用.

If both missing and present keys are to be handled then your first option is useful.

if key in my_dict:
    value = my_dict[key]
    # Do something

在这种特定情况下,使用get不会提供任何优势.相反,您必须找到一个无冲突的值来标识缺少键的条件.

The use of get doesn't provide any advantage in this specific situation. In contrary, you have to find a non-conflicting value to identify the missing key condition.

这篇关于检查key是否存在并在Python中同时获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆