When a key gets stuck in a lock, it's usually because the key or the lock mechanism needs lubrication. The teeth of the key lodge against the lock pins, and even though the pin springs aren't very strong, the pins can be unmovable. If you happen to have some spray lubricant in the car or the garage, you can usually unstick the key fairly quickly. When you don't have the luxury of a ready supply of lubricant, other tricks may work, depending on whether you're trying to open the door to your car or to the house.
Jiggle the key while pulling outward gently. Avoid pulling hard, which merely binds the key against the lock pins. The up-and-down motion of jiggling may free the teeth that are stuck in the lock pins so you can pull out the key.
Wrap one or two ice cubes in a plastic bag and hold them against the key. This may contract the metal enough for the teeth to clear the pins. This strategy works best in warm weather.
Stabilize the lock mechanism by pushing against it with one finger or hand while you turn the key with the other hand. This often helps when you're trying to open a door in a house because the lock mechanism is sometimes loose. Holding the lock steady prevents it from turning with the key.
Spray a quick spurt of spray lubricant into the key hole just above the key while you jiggle the lock with the other hand. More often than not, this is all you need to do to free the key.