使用Python字典,最好检查键是否存在或捕获异常?

时间:2019-02-07 08:56:44

标签: python dictionary

我编写的代码主要使用Python字典来增加一些计数器(计数器的数量不固定)

常见的模式是:

if not key in dictionary1:
    dictionary1[key] = init()
dictionary[key]["last_value"] += current_value

为了加快代码执行速度,最好写一个try-catch子句而不是条件语句?

例如,

try:
  dictionary[key]["last_value"] += current_value
except KeyError:
  dictionary[key] = init()
  dictionary[key]["last_value"] += current_value

3 个答案:

答案 0 :(得分:4)

使用defaultdict

from collections import defaultdict

dictionary = defaultdict(init)
dictionary[key]["last_value"] += current_value

如果key不在字典中时,将添加init()给定的值。

答案 1 :(得分:1)

此处可以使用类似dictionary.get(key, default)的外观。至于try-catch,请将其用于合法的异常处理。

您可能必须这样做:

if dictionary.get(key, None) is None:
    dictionary[key] = init()

dictionary[key]["last_value"] += current_value

答案 2 :(得分:1)

更Python化的方式是:请求宽恕,而不是获得许可。但是正如您所看到的,您将不得不加倍代码,这也是不好的。

幸运的是,还有另一种解决方案:

dictionary.setdefault(key, init())["value"] += current_value

因此,如果dictionary不包含keysetdefault将创建它,并将init的结果分配给它。然后,您可以分配自己的值。

注意::如L3viatan的评论中所述,如果init()除了返回值(如操纵全局变量或执行非常时间)以外的其他操作,这不是一个好选择大量的工作,因为每次执行此行时都会调用init()。返回的值将被忽略。

相关问题