提取前输入字典

2024-06-26 11:09:35 发布

您现在位置:Python中文网/ 问答频道 /正文

在提取元素并将其用于比较之前,检查元素是否在字典中的“pythonic”方法是什么?你知道吗

例如:

现在,我知道了

if "key1" in list2 and list2["key1"]=="5":
  print "correct"

因此,如果它失败,它将在第一个条件下短路。但是,这会导致长条件语句。你知道吗

然而,有没有一种更“python”的方法?我猜在try-catch中包装条件是一个更糟糕的主意。你知道吗


Tags: and方法in元素if字典语句pythonic
3条回答
if list2.get("key1")==5:
    print("correct")

不过,我不会把字典叫做“list2”。你知道吗

如果该值可以为“无”,则可以选择其他默认值:

if list2.get("key1", object()) in my_other_list:
    print("correct")

或者使用例外,或者你的“长”路。你知道吗

不-尝试/例外是绝对好的:

try:
    if list2['key1'] == '5':
        # do something
except KeyError:
    # key wasn't found
except ValueError:
    # most likely value wasn't comparable...

这种方法完全是Python式的。另一个稍有不同的是

if list2.get("key1", <-1,0 or any sensible default, e.g. None>) == 5:
    print "correct"

通过这种方法,您可以使用^{}方法,该方法允许从dict中安全地提取值(并提供了一种指定默认值的方法)

相关问题 更多 >