处理字典中的键错误的最佳方法 [英] Best way to handle a keyerror in a dict
问题描述
当我尝试从字典中获取值时,我想知道处理键盘错误的最佳方法.
I would like to know the best way to handle a keyerror, when I try to get a value from a dict.
我需要这个,因为我的字典包含一些事件的计数.每当发生事件时,我都会从dict中获取计数并对其进行递增并放回原处.
I need this because my dict holds the counts of some events. And whenever an event occurs I take the count from the dict and increment it and put it back.
我在网上找到了一些解决方案,但是它们是针对其他一些语言的.感谢您的帮助.
I found some solutions online, but they were for some other languages. Any help is appreciated.
我现在正在处理keyerror异常.想知道最好的方法来处理字典中的键盘错误.
I am handling the keyerror exception now. Would like to know the best approach to handle a keyerror in a dictionary.
注意:这不是要对列表中的项目进行计数,而是要从dict检索值(不存在)时处理异常.
Note: This is not about counting items in a list but about handling exception when retrieving a value(that does not exist) from a dict.
推荐答案
如果要使用dict
mydict[key] = mydict.get(key, 0) + 1
或者您可以处理KeyError
try:
mydict[key] += 1
except KeyError:
mydict[key] = 1
或者您可以使用defaultdict
from collections import defaultdict
mydict = defaultdict(int)
mydict[key] += 1
这篇关于处理字典中的键错误的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!