How does it work? I've read that its about the similarity of the energy levels of $3d$ and $3p$, but shouldn't the electron shell $4s$ be filled before $3d$ if filled? So what is done with the $3d$?
I'd also like to know in what cases will atoms of elements expand their valence electrons? Which blocks or groups or periods do this?
You're right! The 4s subshell is filled before 3d. Electrons fill the shell with least energy first and the 4s shell has a lower energy than the 3d subshell. Use the Aufbau Principle to find the shell with least energy.
Basically it says that shells with a lower n+l (n and l are the principal and azimuthal quantum numbers) value are filled first. If two shells have the same n+l value, then the shell with lower n is filled first. There are a few exceptions to this rule - Copper, Chromium, Palladium, etc.
Reason: n+l gives the number of nodes in an orbital. The more the number of nodes, the less stable the orbital and so the higher the energy.
Valence shells are filled in the s and p blocks. The inner shells are filled in the d and f blocks.
Anything below the carbon row can expand their octets. The question makes little sense in any other context.