[英]checking if key's already in dictionary with try except
我正在使用字典來計算不同項目在數據集中出現的次數。 在類的初始化中,我將屬性創建為像這樣的字典
self.number_found = {}
第一次找到任何特定項目時,如果我嘗試執行此操作,則會收到KeyError,因為該項目不在詞典中
self.number_found[item] = 1
所以我最終創建了一個函數,用於檢查字典中是否已經有條目,如果沒有,則將其首次添加
def _count_occurrences(self, item):
try:
#this checks to see if the item's already in the dict
self.number_found[item] = self.number_found[item] + 1
x = self.number_found[item]
except KeyError:
x = 1
#this adds an item if not in the dict
self.number_found[item] = x
return x
但是,如果我在數據集中發現某項目的第二次出現,這將無法正常工作。
假設我的數據集中有兩個“大象”。 當我將self.number_found
打印到控制台時,這就是我得到的
{'elephant': 1}
{'elephant': None}
當添加第二次出現時出現此錯誤
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
問題:檢查密鑰是否已在字典中的正確方法是什么(並解釋為什么1
變為None
)
您可以使用defaultdict
:
from collections import defaultdict
self.number_found = defaultdict(int)
第一次訪問項目時,其值將默認為0
返回None
,因為您沒有在try
分支中返回任何內容
except塊末尾的返回必須移出。 這樣,兩種情況都返回x
class C(object):
def __init__(self):
self.number_found = {}
def _count_occurrences(self, item):
try:
#this checks to see if the item's already in the dict
self.number_found[item] = self.number_found[item] + 1
x = self.number_found[item]
except KeyError:
x = 1
#this adds an item if not in the dict
self.number_found[item] = x
return x
c = C()
r = c._count_occurrences('elephant')
print r
print c.number_found
r = c._count_occurrences('elephant')
print r
print c.number_found
這是一個先有超額收益的測試運行,然后再將其放入您的OP中:
jcg@jcg:~/code/python/stack_overflow$ python number_found.py
1
{'elephant': 1}
2
{'elephant': 2}
jcg@jcg:~/code/python/stack_overflow$ python number_found.py
1
{'elephant': 1}
None
{'elephant': 2}
如您所見,第二個版本返回None,因為_count_occurrences try塊沒有返回
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.