KunalMZ KunalMZ - 9 months ago 64
Python Question

Can insertion in dictionary cause KeyError?

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):
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.


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. :)