Magnetic control of the valley degree of freedom of massive Dirac fermions with application to transition metal dichalcogenides