Editor

Safe Dictionary Lookup

Advanced · Write the code · from Python Try-Except: Handle Errors Without Crashing

From the lesson: Python Try-Except: Handle Errors Without Crashing

Imagine a trapeze artist performing high above the ground. No matter how skilled they are, there's always a safety net below. If they slip, the net catches them and they can climb back up and try again.

Read the lesson

Write a function called safe_lookup(data, key, index) that:

1. Looks up key in the dictionary data (which should return a list)

2. Then returns the item at position index in that list

3. Handles these errors:

- KeyError: print "Key 'X' not found" (where X is the key)

- IndexError: print "Index X out of range" (where X is the index)

- TypeError: print "Invalid operation"

Return None for any error case.

Test with these three calls:

  • safe_lookup({"grades": [90, 85, 92]}, "grades", 1) (should print 85)
  • safe_lookup({"grades": [90, 85, 92]}, "scores", 0) (KeyError)
  • safe_lookup({"grades": [90, 85, 92]}, "grades", 10) (IndexError)
  • # Write your safe_lookup function here
    # Test it

    More Try-Except exercises

    All Python exercises · 50 practice problems · Error Handling quiz