Handling missing keys in Python dictionaries (original) (raw)

Last Updated : 13 Nov, 2025

In Python, dictionaries are key-value containers that provide fast access to data with a time complexity of O(1). However, in many applications, the user may not know all the keys present in a dictionary. Accessing a missing key directly results in a **KeyError.

**For Example:

Python `

dic = {'a': 1, 'b': 2}

print("The value associated with 'c' is:") print(dic['c'])

`

**Output

KeyError: 'c'

Notice that key = 'c' doesn't exist in the dictionary and that's why accessing it is giving KeyError.

Below are different methods of handling this in Python:

Using defaultdict

defaultdict from the collections module is highly efficient and avoids repeatedly writing checks. It allows you to set a default value for missing keys at the time of dictionary creation.

Python `

from collections import defaultdict dic = defaultdict(lambda: 'Key Not found')

dic['a'] = 1 dic['b'] = 2 print(dic['a']) print(dic['c'])

`

**Explanation:

Using get() Method

get() method allows you to retrieve a value if the key exists, or return a default value otherwise.

Python `

dic= {'India': '0091', 'Australia': '0025', 'Nepal': '00977'}

print(dic.get('India', 'Not Found'))
print(dic.get('Japan', 'Not Found'))

`

**Explanation:

Using setdefault() Method

setdefault() method works like get(), but if the key is missing, it creates the key with a default value.

Python `

dic = {'India': '0091', 'Australia': '0025', 'Nepal': '00977'} dic.setdefault('Japan', 'Not Present')

print(dic['India']) print(dic['Japan'])

`

**Explanation:

Using try-except Block

You can handle missing keys by catching the KeyError exception

Python `

dic = {'India': '0091', 'Australia': '0025', 'Nepal': '00977'} try: print(dic['India']) print(dic['USA']) except KeyError: print('Not Found')

`

**Explanation:

Using if key in dict

Python `

dic = {'a': 5, 'c': 8, 'e': 2} if 'q' in dic: print(dic['q']) else: print("Key not found")

`