Python - Dictionary Avoiding missing-key errors

Introduction

You can use the following ways to fill in a default value instead of getting an error message for missing key.

  • you can test for keys ahead of time in if statements,
  • use a try statement to catch and recover from the exception explicitly, or
  • use the dictionary get method shown earlier to provide a default for keys that do not exist.

Demo

Matrix = {} 
Matrix[(2, 3, 4)] = 88 #   w ww.  ja v  a  2 s. c  o m
Matrix[(7, 8, 9)] = 99 

if (2, 3, 6) in Matrix:            # Check for key before fetch 
     print(Matrix[(2, 3, 6)])       # See Chapters 10 and 12 for if/else 
else: 
     print(0) 

try: 
    print(Matrix[(2, 3, 6)])       # Try to index 
except KeyError:                   # Catch and recover 
    print(0)                       # See Chapters 10 and 34 for try/except 

 
print( Matrix.get((2, 3, 4), 0) )           # Exists: fetch and return 
print( Matrix.get((2, 3, 6), 0) )           # Doesn't exist: use default arg

Result

Related Topic