我经常发现自己使用字典来计算某事物的出现次数,我想知道是否有办法在不使用例外的情况下更顺畅地进行此操作。
count_dict = {}
for file in files:
############
#parse file#
############
for line in lines:
tokens = line.split()
if "something" in tokens:
try:
count_dict[tokens[0]] += 1
except KeyError:
count_dict[tokens[0]] = 1