Fixes code that could produce KeyError in sorting methods