gh-132983: Refactor shared code in train_dict and finalize_dict (GH-134432) Refactor shared code in train_dict and finalize_dict