Psalm 54 was written by King David when the Ziphites betrayed him. There were two betrayals by the Ziphites in collusion with Saul, we find it in 1 Samuel 23 and 1 Samuel 26, although according to analysts this psalm is more in line with the betrayal in 1 Samuel 23. So, this psalm is a song of gratitude God for freeing him from the Ziphites.
In the first verses of this Psalm we see David pleading with God to listen to him and free him from his enemies (the Ziphites):
19 Then came up the Ziphites to Saul to Gibeah, saying, Doth not David hide himself with us in strong holds in the wood, in the hill of Hachilah, which is on the south of Jeshimon?
20 Now therefore, O king, come down according to all the desire of thy soul to come down; and our part shall be to deliver him into the king’s hand.
21 And Saul said, Blessed be ye of the Lord; for ye have compassion on me.
1 Samuel 23:19-21