×

Handling missing keys in Python dictionaries

In this lesson, you will discover how to create a Python application that will manage missing keys in a dictionary. Python dictionaries store data as key-value pairs, where each value has a distinct key.

A user may attempt to access a key that they are unaware is either existent or absent in a dictionary.

Since the user will encounter an exception or runtime error in this scenario, we must create a program that can deal with missing keys without raising any errors.

Let's look at the program's input-output values.

Input:
Dict_jtp={'x':1, 'y': 2, 'z': 3}
key= a
Output: Traceback (most recent call last):
  File "<string>", line 2, in <module>
NameError: name 'a' is not defined

These methods can be used to address this issue:

  1. Using get() method in the python for dictionary.
  2. Using setdefault() method in the python for dictionary.
  3. Using defaultdict method in python.

Method 1: use the get() command:

In this strategy, we'll employ the get() method. In this method, the Key and a default value will be passed. This method will return the value of the Key if it can be found in the dictionary; else, it will return the default value.

Algorithm

For a better understanding of the strategy, follow the algorithm.

Step 1: Create a values-only dictionary

Step 2: Call get() and pass a default value along with the Key whose value has to be printed.

Step 3: The value of the Key will be printed if the Key is present.

Step 4: The default value will be displayed if not.

Python Program to explain the get() method.

To understand how the abovementioned strategy is implemented, look at the program. Cities' codes have been used as keys in a dictionary, and their real names have been used as values.

Input:
dict_jtp = { 'Hyd': 'Hyderabad', 'Dl' :' Delhi' , 'Mum' : 'Mumbai' , 'BGL' : 'Bengaluru' }
print( dict_jtp.get ( 'Hyd' , 'Not Found' ) )
print( dict_jtp.get ( 'Dl', 'Delhi') )
print( dict_jtp.get( 'Kol' , 'Not Found' ))
Output:
Hyderabad
Delhi
Not Found

Method 2:using the setdefault() method in python for the dictionary.

If the Key is found in the dictionary, the setdefault() method operates similarly to the get() method and returns the value of the Key. If the Key is missing, this method will generate a new key using the argument's default value as its value if the Key is not present.

Algorithm

For a better understanding of the strategy, follow the algorithm.

Step 1: Create a values-only dictionary

Step 2: Call setdefault() and provide a default value along with the Key whose value has to be checked.

Step 3: The value of the Key will be printed if the Key is present.

Step 4: If not, the method will create a new key and set its value to the default.

Input:
 dict_jtp = { 'Hyd' : 'Hyderabad' , 'Dl' :' Delhi' , 'Mum' : 'Mumbai' , 'BGL' : 'Bengaluru' }
# default value in the python 
dic.setdefault('WBL', 'Not Found')
# key is presented in the python 
print(dic['Hyd'])
#key is not present in python.
print(dic['WBL'])
Output:
Hyderabad
Not Found.

Method 3:using defaultdict method in the python.

If the Key cannot be located, the default dict subclass of the dictionary class returns an object without reporting any issues. A typical dictionary will always provide an error if the Key is missing from the dictionary. A function is accepted as an argument.

Algorithm

For a better understanding of the strategy, follow the algorithm.

Step 1: import the collections.

Step 2:Declare the defaultdict.

Step 3: Initialize the values and keys.

Step 4: Use keys to print the values

To understand how the strategy mentioned above is implemented, look at the program. We need to import collections into our program before we can utilize defaultdict. A lambda function has been defined and is used as an argument in the defaultdict.

Input:

import collections
# declaring defaultdict in the python to handle the error with the dictionary. 
Dict_jtp = collections.defaultdict(lambda: 'Key is not present')
# initialize keys and their values in the program.
Dict_jtp['Hyd’]='Hyderabad'
Dic_jt[['MUM']='Mumbai'
# key is present in the python program.
print(dict_jtp['HYD'])
#key is not presented in the python program.
print(dict_jtp['Ram'])
Output:
Hyderabad
The Key is not present.

Related Topics

Python: SetBitmap() function in wxPython

SetBitmap() function In the last tutorial, we have discussed about the GetLabelText() function of wx.MenuItem class which is one of the important function of this class. Now, in this tutorial, we...

6 minutes read.

Linear Regression using Sklearn with Example

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

Write Dictionary to CSV in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

4 minutes read.

NOT IN operator in Python

This page contains all the information about “not in” operator in python. You can also know everything about what type of operator is “not in” in python language and where...

7 minutes read.

What is the Python Global Interpreter Lock?

Introduction When working with processes, Python employs a form of process lock called the Global Interpreter Lock (GIL). Python typically executes a collection of typed statements using just one thread. It...

4 minutes read.

Difference between Perl and Python

Control and presently utilized for a great many undertakings, including framework organization, web improvement, network programming, and GUI improvement, and the sky is the limit from there. About Perl? Perl is a...

4 minutes read.

Introduction to Scratch programming

Scratch programming is generally designed for children who may create digital stories, games, and animations using the computer language Scratch, which has the largest kid-focused community in the world. Scratch...

3 minutes read.

Writing to Excel using Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

3 minutes read.

Collections in python

In this tutorial, we will see what is collection in python.  Further, we will see in-depth the different kinds of collections in python. Collections Collections in python are the built-in module used...

9 minutes read.

Python Dictionary copy() method

Python Dictionary copy() method The dictionary.copy () method in Python returns a copy of the specified dictionary. Syntax dictionary.copy () Parameter NA Return None Example 1 # Python program explaining # the dictionary.copy() method # initialising the dictionary ...

1 minute read.

Best Database in Python

In this tutorial, Firstly, we will understand what the term database means. Further, we will see the various databases supported in Python and when to use which one. Further, we...

7 minutes read.

Palindrome program in Python

Palindrome program in python A number or string is said to be a palindrome if we invert the number or string and the string or number remains the same as the...

3 minutes read.

Iterate a Dictionary in Python

In this tutorial, we will learn how to Iterate a Dictionary in Python. Dictionary: In Python, a dictionary is an unordered collection of data values that is used to store data values,...

3 minutes read.

Data Drop in Python

Introduction You'll understand how to delete a group of rows from a Pandas dataframe in this article.You can read this article on How to Drop Columns in Pandas to find out...

6 minutes read.

GUI to extract lyrics from a song Using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

4 minutes read.

Speech Recognition Module in Python

Speech Module in Python: Converting text to speech, known as Speech Synthesis, this process is the computer-generated recreation of human speech. This module converts the human language text into human-like...

8 minutes read.

Python Time Library

We will consider various functions given by the python module library with examples.This python time module helps to work on time in python to get the current time.Before going with...

4 minutes read.

Yield vs Return in Python

In this article, you will learn about " Yield " and " Return " in Python. You will also understand the difference between " Yield " and " Return "...

6 minutes read.

Python Set intersection() method

Python Set intersection() method The set.intersection() method in Python returns a new set with elements that are similar between two or more sets. Syntax set.intersection(set1, set2 ... etc) Parameter set1- This parameter represents the set to search for...

2 minutes read.

Salary of Python Developers in India

In this tutorial, we will understand who python developers are and what is their salary when they work in India. Python Developers Python Developers are the people who are involved in designing...

4 minutes read.