Python 检查键';它已在字典中,请尝试例外

Python 检查键';它已在字典中,请尝试例外,python,Python,我使用字典计算数据集中不同项目出现的次数。在类的init中,我创建了一个字典属性,如下所示 self.number_found = {} 当我第一次发现任何特定项时,如果我尝试这样做,我会得到一个keyrerror,因为该项还不在字典中 self.number_found[item] = 1 因此,我最终创建了一个函数来检查一个条目是否已经在字典中,如果没有,则第一次添加它 def _count_occurrences(self, item): try: #thi

我使用字典计算数据集中不同项目出现的次数。在类的init中,我创建了一个字典属性,如下所示

self.number_found = {}
当我第一次发现任何特定项时,如果我尝试这样做,我会得到一个keyrerror,因为该项还不在字典中

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\u打印到控制台时,这就是我得到的

{'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
下面是一个测试运行,首先使用outdented return,然后在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_events try块返回

谢谢,您能解释一下为什么将1更改为None(按照OP中的要求)是您的return x语句缩进正确吗?这就是该方法的用途:
d[item]=d.get(item,0)
。可能会有帮助。