Fuller implementation of foldByKey