mercredi 29 juin 2016

checking if key's already in dictionary with try except

I'm using a dictionary to count how many times different items appear in a dataset. In the init of the class, I create the property as a dictionary like this

self.number_found = {}

The first time I find any particular item, I would get a KeyError if I try to do this because the item isn't in the dictionary yet

self.number_found[item] = 1

so I ended up creating a function that checks if an entry is already in the dictionary and if not, adds it for the first time

 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

However, this is not working as intended if I find a second occurrence of an item in a dataset.

Let's say there are two 'elephant' in my dataset. When I print self.number_found to the console this is what I get

{'elephant': 1}
{'elephant': None}

and I get this error when adding the second occurrence

TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Question: what's the right way to check if the key's already in the dictionary (with an explanation as to why the 1 is changing to a None)

Aucun commentaire:

Enregistrer un commentaire