refactored key iteration logic