Side-by-side comparison of AttributeError and KeyError — understand the differences, causes, and fixes.
AttributeErrorAn object does not have the requested attribute or method.
You tried to access an attribute or method that does not exist on the object. The object may be None when you expected a different type, the method name may be misspelled, or you may be using a wrong type.
Check the object's type with type(obj). Use hasattr(obj, 'attr') to check before accessing. Add None checks for objects that might be None. Use dir(obj) to list available attributes. Check the class documentation.
KeyErrorA dictionary key was not found in the dictionary.
You tried to access a dictionary key that does not exist. The key may be misspelled, the data structure may be different than expected, or the key was not yet added to the dictionary.
Use dict.get(key, default) to provide a default value. Check key existence with 'if key in dict'. Use collections.defaultdict for auto-initialized values. Use try-except KeyError for expected missing keys.