Can insertion in dictionary cause KeyError?


Keywords:python 


Question: 

Can this code ever produce KeyError? I'm new to python, just want some clarification as I checked insertion can't cause KeyError Exception.

def add(self, name, company):
    try:
        self.identity[self.id] = { 'name': name,
                                   'company': company }
        return self.identity
    except KeyError:
        raise NameNotAdded

Here identity is a Dictionary and id is an int initialized somewhere else and NameNotAdded is a custom exception.


2 Answers: 

Insertion will never raise a KeyError, but it can raise TypeError if you supply a bad key, and that generally means you're trying to use a mutable object as a key. Python integers are immutable, so they won't raise a TypeError.

Note that if you try to add too many items to your dict you will get a MemoryError due to lack of available RAM, or an OverflowError because you've attempted to exceed the maximum size of a collection (which can be read from sys.maxsize). But there's not much point bothering to catch those. :)



There is no any reason in that case to throw exception about KeyError.

A KeyError generally means the key doesn't exist. In your case you just adds a new key to your dictionary.