# How does the term $|\psi\rangle\langle\psi|$ come from while calculating the expectation value? [duplicate]

Suppose there're two systems $$A$$ and $$B$$, if we're in a pure state $$|\psi\rangle\in\mathbb{H}_a\otimes\mathbb{H}_b$$, let $$\hat A$$ be an operator acts on $$\mathbb{H}_a$$, and $$|\psi\rangle=\sum_{i,j}\psi_{i,j}|a_i\rangle|b_j\rangle$$. Then, the expectation value of A with respect to the state $$|\psi\rangle$$ can be calculated as: $$\langle A\rangle_{\psi}= Tr_{\mathbb{H}_a\otimes\mathbb{H}_b}(A|\psi\rangle\langle\psi|)=\sum_{i,j}\langle a_i|\langle b_j|A\otimes\mathbb{1}_B|\psi\rangle\langle\psi|a_i\rangle|b_j\rangle=...$$

I'm very confused how those two equalities coming from? Especially for the term $$|\psi\rangle\langle\psi|$$ in the sum, can I understand their function as generating a $$\psi$$ matrix with different constants $$\psi_{i,j}$$? Thanks!!

That is the definition of the expectation value of an operator $$A$$ using the trace
$$\langle A \rangle = Tr (\rho A)$$
$$\rho = \mid \psi \rangle \langle \psi \mid$$