繁体   English   中英

使用尝试检查键是否已在字典中

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM