Swiatek, a two-time Grand Slam champion, hasn't gotten past the round of 16 in four tournaments since winning the French Open in June.
The win was the 24th-ranked Keys' first in six matches against a top-ranked opponent. She had never won a set against a No. 1 player.
After dropping the first set and losing the first five games of the second, Swiatek rallied to win four straight, fighting off one match point before Keys clinched with a forehand winner to the ad court off a shot that clipped the net.
Swiatek won her first two matches against Keys, including 6-1, 6-0 this year at Indian Wells.
"Obviously, there were a couple of games where I had match point," Keys said in an on-court interview. "She beat me pretty badly the last time we played, so I was happy to get the win."
No. 1 Daniil Medvedev advanced to the quarterfinals with a 7-5, 7-5 win over Denis Shapovalov. Medvedev is trying to shake off a second-round loss to Nick Kyrgios last week in Montreal and hone his game for the upcoming US Open.
"In general, I managed to be pretty constant," Medvedev said. "I got a lot of break opportunities. I served pretty well, even in the game where I lost my serve. In general, I'm happy with my level and looking forward to the next matches."