OK, so let's run a bit with the "Discord isn't such a bad guy after all" ball and see if we score, shall we?
Discord knows from the moment he pops into view that Twilight's upset about her place in the world. Also, he basically figured out her problem for her, and did everything but hold up a flashing neon sign pointing at their Friendship Journal™ saying "ANSWERS ARE HERE". He even helpfully bookmarked the darn thing for her.
It's not too far a leap to say that he figured out what the keys were from that alone- and from there, that the items the 5 got were, if not the keys themselves, at least connected to them. And if you're Discord, and you think that the keys are mundane items that were given to each of the Mane 6 as tokens of friendship, well, then you're already home free, aren't you? Because
But obviously, that wasn't it. So Discord's stuck playing the long game with Tirek, and he learns that Tirek plans on ransoming Twilight's friends back to her in exchange for her alicorn magic.
Which, again, is JUST FINE. Because Discord knows first-hand that Twilight + magic isn't what's invincible, it's Twilight + her friends. If Tirek just wants to hand them over to her on a platter, well, it's his problem to solve, isn't it? If Discord was truly fully on Tirek's side, he'd have said "Hey, maybe you want to keep that one away from her friends. Worked for me, at least for a while."
From there, things progress rather predictably- Discord gives Twilight his medallion (rather dramatically, even for him in his state), and rainbow friendship magic etc.
It's not all provable, and if you still think Discord was a jerk for pretty much the whole episode, I can't blame you. But I can't believe all the little things here lined up by accident.