Handle a missing dictionary key

EasyException Handling Programs · 3 of 20

Write a Python program that reads a key from a dictionary and handles a missing key.

Advertisement
Output
missing key: 'timeout'
30

Approach

  1. Catch KeyError; compare with dict.get().

Solution

Python
config = {"browser": "chromium"}try:    print(config["timeout"])except KeyError as e:    print("missing key:", e)print(config.get("timeout", 30))
Output
missing key: 'timeout'
30

Line by line

Line 6

get with a default avoids the exception entirely when a default makes sense.

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Leave a Comment