When two objects come in contact, they can exchange charges between them and become two oppositely charged objects. It can happen when you sit on a chair. When you leave the chair, you will carry this extra charge that will try to get out of you at the first opportunity. This is why static shock occurs so often when people go from a chair or a couch to touch a door knob. The key to prevent the static shock is to reduce the charge built up on you and take simple precautionary actions.
Avoid shoes with soles made of rubber. Some rubbers acts as an insulator and can build more charges. Leather shoes don't conduct much static.
Use moisturizing cream and moisturize yourself. You may have noticed that you get this static shock when it is dry. Moisture in the air or your body reduces charge build up.
Touch a nonconducting object like wood before you touch the metallic knob. The wood will absorb some of the charges and reduce the risk of shock.
Touch the knob with the key first. The key will take the brunt of the static shock, and you may even get to see a little spark.