Python - Dictionary Missing Keys: if Tests

Introduction

Dictionaries support accessing items by key only.

Fetching a nonexistent key is a mistake:

Demo

D = {'a': 1, 'b': 2, 'c': 3} 
print( D )#   w w w  . j  ava  2  s  .  c om
D['e'] = 99                      # Assigning new keys grows dictionaries 
print( D )
D['f']                           # Referencing a nonexistent key is an error

Result

We can use if not to check if a key is in a dictionary.

Demo

D = {'a': 1, 'b': 2, 'c': 3} 
print( D )# from  ww  w  .j  av  a2  s  .  co  m

print( 'f' in D )

if not 'f' in D:                           # Python's sole selection statement 
    print('missing')

Result

Related Topic