Why is $\frac{d^2}{dx^2}=\left(\frac{d}{dx}\right)^2$ justified in the equation for the square of the momentum operator? The square of the momentum operator $\hat p$ from the time independent Schrödinger equation is $$\hat p^2=-\hbar^2\frac{d^2}{dx^2}\tag{1}$$ in the one dimensional case. 
So if we solve this equation for $\hat p$ we obtain $$\hat p=-i\hbar\frac{d}{dx}$$ the overall minus sign is subjective but there is one major problem I have with equation $(1)$: 
It assumes that $$\frac{d^2}{dx^2}=\left(\frac{d}{dx}\right)^2\tag{2}$$
Now we know that in general $$\frac{d^2}{dx^2}\ne\left(\frac{d}{dx}\right)^2$$
So why does equation $(2)$ hold in this particular case?
 A: It is a matter of notation, for an operator $\hat{O}$ the meaning of $\hat{O}^2$ is simply $\hat{O}\hat{O}$, so that
$$
\left(\frac{d}{dx}\right)^2 = \frac{d}{dx}\frac{d}{dx} = \frac{d^2}{dx^2}
$$
A: Let us calculate the representation of the operator $\hat{p}^2$ onto the position basis, namely $\langle x|\hat{p}^2|\psi\rangle$. 
One has:
$$
\langle x|\hat{p}^2|\psi\rangle = \langle x|\hat{p}\hat{p}|\psi\rangle = \int dx' \langle x|\hat{p}|x'\rangle\langle x'|\hat{p}|\psi\rangle = \int dx' (-i\hbar)\frac{\partial}{\partial x}\delta(x-x')\cdot (-i\hbar)\frac{\partial}{\partial x'}\psi(x')
$$
integrating by part one obtains:
$$
-\hbar^2(-1)\int dx' \delta(x-x') \frac{\partial^2}{\partial x'^2}\psi(x') = -\hbar^2 \frac{\partial^2}{\partial x^2}\psi(x)
$$
and likewise for any higher power.
A: I think you may be getting a bit confused by the assertion:
$$\frac{\mathrm{d}^2\, y(x)}{\mathrm{d} \,x^2} \neq \left(\frac{\mathrm{d} \,y(x)}{\mathrm{d}\, x}\right)^2$$
I agree the interpretation is somewhat subtle, but $\left(\frac{\mathrm{d}}{\mathrm{d} \,x}\right)^2$ is simply meant to mean "the operator $\frac{\mathrm{d}}{\mathrm{d} \,x}$ imparted twice". The context helps here: in QM we always talk about linear terms and operator equations, so a square almost always stands for "impart twice". 
