Optimize dictionary search code