We determine the average size of the 3-torsion in class groups of $G$-extensions of a number field when $G$ is any transitive $2$-group containing a transposition, for example $D_4$. It follows from the Cohen--Lenstra--Martinet heuristics that the average size of the $p$-torsion in class groups of $G$-extensions of a number field is conjecturally finite for any $G$ and most $p$ (including $p\nmid|G|$). Previously this conjecture had only been proven in the cases of $G=S_2$ with $p=3$ and $G=S_3$ with $p=2$. We also show that the average $3$-torsion in a certain relative class group for these $G$-extensions is as predicted by Cohen and Martinet, proving new cases of the Cohen--Lenstra--Martinet heuristics. Our new method also works for many other permutation groups $G$ that are not $2$-groups.