Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Handling missing keys in Python dictionaries
Next article icon

Handling missing keys in Python dictionaries

Last Updated : 22 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, dictionaries are containers that map one key to its value with access time complexity to be O(1). But in many applications, the user doesn't know all the keys present in the dictionaries. In such instances, if the user tries to access a missing key, an error is popped indicating missing keys. 

Handling Missing Keys in Python Dictionaries

In the example, no key named 'c' in the dictionary popped a runtime error. To avoid such conditions, and to make the aware user that a particular key is absent or to pop a default message in that place, there are several methods to handle missing keys.

Python3
# Python code to demonstrate Dictionary and # missing value error d = { 'a' : 1 , 'b' : 2 }  # trying to output value of absent key  print ("The value associated with 'c' is : ") print (d['c']) 

Error : 

Traceback (most recent call last):   File "46a9aac96614587f5b794e451a8f4f5f.py", line 9, in      print (d['c']) KeyError: 'c'

Handling Missing Keys in Python Dictionaries

There are the methods to handle missing keys in Python Dictionaries.

  • Using key
  • Using get()
  • Using setdefault()
  • Using defaultdict()
  • Using try-except block

Python Program to Handling Missing keys in Python Dictionaries Using key

It is the basic way to solve key errors using if-else condition. To check if the key is present or not.

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

Output
Key not found 

Python Program to Handling Missing keys in Dictionaries Using get()

get(key,def_val) method is useful when we have to check for the key. If the key is present, the value associated with the key is printed, else the def_value passed in arguments is returned.

Python3
country_code = {'India' : '0091',                 'Australia' : '0025',                 'Nepal' : '00977'}  # search dictionary for country code of India print(country_code.get('India', 'Not Found'))  # search dictionary for country code of Japan print(country_code.get('Japan', 'Not Found')) 

Output
0091 Not Found 

Handling Missing keys in Python Dictionaries Using setdefault()

setdefault(key, def_value) works in a similar way as to get(), but the difference is that each time a key is absent, a new key is created with the def_value associated with the key passed in arguments. In this example, we are using setdefault() function to handle the missing keys.

Python3
country_code = {'India' : '0091',                 'Australia' : '0025',                 'Nepal' : '00977'}  # Set a default value for Japan country_code.setdefault('Japan', 'Not Present')   # search dictionary for country code of India print(country_code['India'])  # search dictionary for country code of Japan print(country_code['Japan']) 

Output
0091 Not Present 

Python Program to Handling Missing keys in Python Dictionaries Using defaultdict

"defaultdict" is a container that is defined in a module named "collections". It takes a function(default factory) as its argument. By default, the default factory is set to "int" i.e 0. If a key is not present in the defaultdict, the default factory value is returned and displayed. It has advantages over get() or setdefault().  

  • A default value is set at the declaration. There is no need to invoke the function again and again and pass the similar values as arguments. Hence saving time.
  • The implementation of defaultdict is faster than get() or setdefault().

 In this example, we are using defaultdict to check if the key is present or not and set default value "key not found" to the absent keys by using lambda.

Python3
# Python code to demonstrate defaultdict import collections  # declaring defaultdict # sets default value 'Key Not found' to absent keys defd = collections.defaultdict(lambda : 'Key Not found')  # initializing values  defd['a'] = 1  # initializing values  defd['b'] = 2  # printing value  print ("The value associated with 'a' is : ",end="") print (defd['a'])  # printing value associated with 'c' print ("The value associated with 'c' is : ",end="") print (defd['c']) 

Output
The value associated with 'a' is : 1 The value associated with 'c' is : Key Not found 

Handling Missing keys in Python Dictionaries Using the try-except block

This program shows how to handle missing keys in Python dictionaries using a try-except block. In this example, we are using try-except block to check whether the key is present or not.

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

Output
0091 Not Found 

Time Complexity: The time complexity of the try-except block is O(1).
Space Complexity: The space complexity of the program depends on the size of the dictionary and the message to be printed in the 'except' block


Next Article
Handling missing keys in Python dictionaries

K

kartik
Improve
Article Tags :
  • Technical Scripter
  • Python
  • python-dict
  • Python dictionary-programs
Practice Tags :
  • python
  • python-dict

Similar Reads

    Dictionaries in Python
    Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier to
    5 min read
    Flatten given list of dictionaries - Python
    We are given a list of dictionaries, and the task is to combine all the key-value pairs into a single dictionary. For example, if we have: d = [{'a': 1}, {'b': 2}, {'c': 3}] then the output will be {'a': 1, 'b': 2, 'c': 3}Using the update() methodIn this method we process each dictionary in the list
    3 min read
    Python Dictionary keys() method
    keys() method in Python dictionary returns a view object that displays a list of all the keys in the dictionary. This view is dynamic, meaning it reflects any changes made to the dictionary (like adding or removing keys) after calling the method. Example:Pythond = {'A': 'Geeks', 'B': 'For', 'C': 'Ge
    2 min read
    Add new keys to a dictionary in Python
    In this article, we will explore various methods to add new keys to a dictionary in Python. Let's explore them with examples:Using Assignment Operator (=)The simplest way to add a new key is by using assignment operator (=).Pythond = {"a": 1, "b": 2} d["c"] = 3 print(d)Output{'a': 1, 'b': 2, 'c': 3}
    2 min read
    How to Add Duplicate Keys in Dictionary - Python
    In Python, dictionaries are used to store key-value pairs. However, dictionaries do not support duplicate keys. In this article, we will explore several techniques to store multiple values for a single dictionary key.Understanding Dictionary Key ConstraintsIn Python, dictionary keys must be unique.
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences