I saw this exchange on Twitter:
»Was denkst du gerade?«
»Ja, das dachte ich mir.«
Why is mir in this sentence? It seems redundant. I assume it is one of the rules of grammar.
Mir is the dative of sich, and the phrase used is es sich denken.
Er brachte Blumen mit. Sie dachte sich schon, dass etwas nicht stimmte.
He brought flowers. She thought to herself something was fishy.
The verb in question is sich etwas denken, meaning a) sub-meaning at the downwards-pointing arrow. In this context, it means to guess something.
Since the verb is reflexive, it requires a reflexive pronoun. And since there is also an accusative object (etwas), the reflexive pronoun in the first and second person forms defaults back to the dative object pronoun. Thus, it must be:
Ich habe mir das gedacht.
Du hast dir das gedacht.
Sie hat sich das gedacht.
Wir haben uns das gedacht.
Ihr habt euch das gedacht.
Sie haben sich das gedacht.
(Side note: I used the perfect form instead of preterite here which is more natural to me as a Bavarian since the dialog is closer to informal, spoken than to formal, written language.)
I think the important point to be emphasized here is that there are different versions of the word "denken", one of which is reflexive and requires a dative pronoun. Its meaning can be said as "imagine", not exactly the original "think" which is the version without reflexive and dative requirement.
For reference see for example https://www.collinsdictionary.com/dictionary/german-english/denken