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 )# from  www.ja  v a  2s.c o  m
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 )#   ww w  .  j  a  va  2  s . c om

print( 'f' in D )

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

Result

Related Topic