×

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 String capitalize() method

Python String capitalize() method The string.capitalize() method in Python returns a copy of the string with only its first character capitalized. Syntax string.capitalize() Parameter NA Return This function returns a string where the first character is upper...

1 minute read.

How to Write a Configuration file in Python

This article will discuss How to write a configuration file in python, why we need config files in Python, the format of the configuration file, file extensions, and how to...

11 minutes read.

Python Marshmallow

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python locals() function

Python locals() function The locals() function in Python updates and returns a dictionary representing the current local symbol table. Syntax locals() Parameter NA Return This function returns the local symbol table as a dictionary or returns free...

1 minute read.

Create First GUI Application 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...

6 minutes read.

Python Command line Arguments

Python Command line Arguments The command-line argument is used to the change functionality of the program. It's an extra command the programmer can use while launching a program. These commands have many uses...

7 minutes read.

Creating Tables using Python MySQL

In this article, we are going to learn how to create tables in databases using Python MySQL. Introduction to Tables: Generally, databases are used in order to store the information in the...

9 minutes read.

Application to get live USD/INR rate Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python Variables, Constants and Literals

Python is today's most valuable, easy-to-implement and sought-out programming language. Nowadays, developers want to focus on implementing the program rather than spending time with complex programs. So, for this reason,...

17 minutes read.

How to build a Virtual Assistant Using Python

What is a virtual assistant? A virtual assistant is a new and very interesting concept in today’s world. When we hear the word “Virtual Assistant”, we can easily visualize “Jarvis or...

8 minutes read.

Length of Tuple in Python

What is Tuple? Python is a data structure in a python programming language; it is the collection of the objects in a sequence. The tuples are immutable; that is, we cannot...

3 minutes read.

GUI Calculator in Python

Introduction In Python, we can develop a GUI(Graphical User Interface) with multiple options. It offers us some great and commonly used methods for the development of the Graphical User Interface. Tkinter...

4 minutes read.

Static Variables in Python

What is a Static Variable? The variable that remains with a constant value throughout the program or throughout the class is known as a " Static Variable ". Static variables are...

3 minutes read.

Front end in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

4 minutes read.

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...

3 minutes read.

Python List Size

Introduction The list data type in Python is an ordered, flexible collection. A list may also contain duplicate entries. To get the size of any object, use the len() function in...

6 minutes read.

Python format() function

Python format() function The format() function in Python formats a specified value into the given format. A ‘TypeErrorexception’ is raised if the method search reaches the object and the format_spec is non-empty, or if either the format_spec or the...

1 minute read.

Speech Recognition in Python

What is Speech Recognition? Speech Recognition is a term defined for automatic recognition of human speech. Speech recognition is the most significant activity in the domain of the interaction between the...

8 minutes read.

Python System Command

To execute a program in Python, we need to execute some shell commands to run our program on the computer. Python will provide some shell commands in our background to...

3 minutes read.

Difference between Mutable and Immutable Objects

Difference between Mutable and Immutable Objects As we all know that Python is an object-oriented programming language. Object-oriented programming approach is based on the objects and the classes’ stores the data...

4 minutes read.