The Wayback Machine - https://web.archive.org/web/20240926210511/https://www.geeksforgeeks.org/handling-missing-keys-python-dictionaries/
Open In App

Handling missing keys in Python dictionaries

Last Updated : 22 Aug, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

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



Similar Reads

Python - Concatenate values with same keys in a list of dictionaries
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform concatenation of all the key values list that is like in dictionary list. This is quite a common problem and has applications in domains such as day-day programming and web development domain. Let's discuss the certain ways in which this task can be
7 min read
Python - Find the Common Keys from two Dictionaries
In this article, we will learn how can we print common keys from two Python dictionaries. We will see that there are multiple methods one can do this task. From brute force solutions of nested loops to optimize ones that trade between space and time to decrease the time complexity we will see different methods to do the task at hand and why they wo
4 min read
Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read
Python | Sort Python Dictionaries by Key or Value
There are two elements in a Python dictionary-keys and values. You can sort the dictionary by keys, values, or both. In this article, we will discuss the methods of sorting dictionaries by key or value using Python. Need for Sorting Dictionary in PythonWe need sorting of data to reduce the complexity of the data and make queries faster and more eff
8 min read
Ways to sort list of dictionaries by values in Python - Using lambda function
In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can
2 min read
Python | Common items among dictionaries
Sometimes, while working with Python, we can come across a problem in which we need to check for the equal items count among two dictionaries. This has an application in cases of web development and other domains as well. Let's discuss certain ways in which this task can be performed. Method #1 : Using dictionary comprehension This particular task
6 min read
Python | Flatten given list of dictionaries
Given a list of the dictionaries, the task is to convert it into single dictionary i.e flattening a list of dictionaries. Given below are a few methods to solve the given task. Method #1: Using Naive Method C/C++ Code # Python code to demonstrate # to flatten list of dictionaries # Initialising dictionary ini_dict = [{'a':1}, {'b':2}, {'c':3}] # pr
4 min read
Python - Remove empty value types in dictionaries list
Sometimes, while working with Python dictionaries, we require to remove all the values that are virtually Null, i.e does not hold any meaningful value and are to be removed before processing data, this can be an empty string, empty list, dictionary, or even 0. This has applications in data preprocessing. Let us discuss certain ways in which this ta
7 min read
Count dictionaries in a list in Python
A list in Python may have items of different types. Sometimes, while working with data, we can have a problem in which we need to find the count of dictionaries in particular list. This can have application in data domains including web development and Machine Learning. Lets discuss certain ways in which this task can be performed. Input : test_lis
5 min read
Building an undirected graph and finding shortest path using Dictionaries in Python
Prerequisites: BFS for a GraphDictionaries in Python In this article, we will be looking at how to build an undirected graph and then find the shortest path between two nodes/vertex of that graph easily using dictionaries in Python Language. Building a Graph using Dictionaries Approach: The idea is to store the adjacency list into the dictionaries,
3 min read
Read List of Dictionaries from File in Python
A dictionary in Python is a collection where every value is mapped to a key. Since they are unordered and there is no constraint on the data type of values and keys stored in the dictionary, it is tricky to read dictionaries from files in Python. Read a List of Dictionary from Text Files in PythonUsing Pickle ModuleUsing read( ) MethodThe problem s
3 min read
Iterate through list of dictionaries in Python
In this article, we will learn how to iterate through a list of dictionaries. List of dictionaries in use: [{'Python': 'Machine Learning', 'R': 'Machine learning'}, {'Python': 'Web development', 'Java Script': 'Web Development', 'HTML': 'Web Development'}, {'C++': 'Game Development', 'Python': 'Game Development'}, {'Java': 'App Development', 'Kotli
3 min read
Python - Convert list of dictionaries to JSON
In this article, we will discuss how to convert a list of dictionaries to JSON in Python. Python Convert List of Dictionaries to JsonBelow are the ways by which we can convert a list of dictionaries to JSON in Python: Using json.dumps()Using json.dump()Using json.JSONEncoderUsing default ParameterDictionaries to JSON in Python Using json.dumps()In
5 min read
Filter List of Dictionaries Based on Key Values in Python
Filtering a list of dictionaries based on key values is a common task in Python, especially when working with data manipulation and analysis. In this article, we will explore five different methods to achieve this goal, each offering its own advantages and use cases. Whether you're a beginner or an experienced Python developer, these methods will p
3 min read
Merge two dictionaries in a single expression in Python
Merging dictionaries is a common task in Python programming, and doing it efficiently and concisely can significantly enhance the readability and performance of your code. With the introduction of newer versions of Python, particularly Python 3.9, the process of merging dictionaries has become more intuitive and elegant. In this article, we'll expl
2 min read
Are Python Dictionaries Ordered?
Yes, as of Python 3.7, dictionaries are ordered. This means that when you iterate over a dictionary, insert items, or view the contents of a dictionary, the elements will be returned in the order in which they were added. This behavior was initially an implementation detail in Python 3.6 (in the CPython implementation) but was made a language featu
3 min read
How to Compare List of Dictionaries in Python
The Python Dictionaries are a powerful data type in Python that allow you to store data as key-value pairs. In this article, we will be discussing how to compare elements in two dictionaries in Python. We will go over the syntax for comparing dictionary elements and will provide examples of how to do so. What is a Dictionary?The dictionary is a dat
3 min read
Python | Merging two Dictionaries
In Python, a dictionary is a data structure that contains the element in the key-value pair in which keys are used to access the values in the dictionary. Python has some inbuilt dictionaries like defaultdict. In this article, we will see various ways to merge two dictionaries. Example Input: dict1 = {'a': 10, 'b': 8} dict2 = {'d': 6, 'c': 4}Output
7 min read
Ways to sort list of dictionaries by values in Python – Using itemgetter
In this article, we will cover how to sort a dictionary by value in Python. To sort a list of dictionaries by the value of the specific key in Python we will use the following method in this article. In everyday programming, sorting has always been a helpful tool. Python's dictionary is frequently utilized in a variety of applications, from those i
2 min read
Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs. Example: Here, The data is stored in key: value pairs in dictionaries, which makes it easier to find values. [GFGTABS] Python Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print(Dict) [/GFGTABS]Output{1: 'Geeks', 2: 'For', 3: 'Geeks'} Python dicti
10 min read
How to convert list of dictionaries into Pyspark DataFrame ?
In this article, we are going to discuss the creation of the Pyspark dataframe from the list of dictionaries. We are going to create a dataframe in PySpark using a list of dictionaries with the help createDataFrame() method. The data attribute takes the list of dictionaries and columns attribute takes the list of names. dataframe = spark.createData
2 min read
Create Pandas Dataframe from Dictionary of Dictionaries
In this article, we will discuss how to create a pandas dataframe from the dictionary of dictionaries in Python. Method 1: Using DataFrame() We can create a dataframe using Pandas.DataFrame() method. Syntax: pandas.DataFrame(dictionary) where pandas are the module that supports DataFrame data structureDataFrame is the datastructure that converts di
2 min read
Handle and Iterate Nested Dictionaries in Django Templates
Django templates offer various tags and filters to work with data. they are designed to readable and expressive. To iterate through a dictionary which contains a dictionary itself as a Value we can use the " { % for % } " template tag to iterate over dictionary that contains dictionary. But Django templates don't support nested dictionary iteration
4 min read
Python | Find missing and additional values in two lists
Given two lists, find the missing and additional values in both the lists. Examples: Input : list1 = [1, 2, 3, 4, 5, 6] list2 = [4, 5, 6, 7, 8] Output : Missing values in list1 = [8, 7] Additional values in list1 = [1, 2, 3] Missing values in list2 = [1, 2, 3] Additional values in list2 = [7, 8] Explanation: Approach: To find the missing elements o
3 min read
Replacing missing values using Pandas in Python
Dataset is a collection of attributes and rows. Data set can have missing data that are represented by NA in Python and in this article, we are going to replace missing values in this article We consider this data set: Dataset In our data contains missing values in quantity, price, bought, forenoon and afternoon columns, So, We can replace missing
2 min read
How to handle missing values of categorical variables in Python?
Machine Learning is the field of study that gives computers the capability to learn without being explicitly programmed. Often we come across datasets in which some values are missing from the columns. This causes problems when we apply a machine learning model to the dataset. This increases the chances of error when we are training the machine lea
4 min read
How to deal with missing values in a Timeseries in Python?
It is common to come across missing values when working with real-world data. Time series data is different from traditional machine learning datasets because it is collected under varying conditions over time. As a result, different mechanisms can be responsible for missing records at different times. These mechanisms are known as missingness mech
10 min read
Fix: "SyntaxError: Missing Parentheses in Call to 'print'" in Python
In Python, if we see the "SyntaxError: Missing Parentheses in Call to 'print'" error, it means we forgot to use parentheses around what we want to print. This is the most common error that we encounter when transitioning from Python 2 to Python 3. This error occurs due to a significant change in how the print statement works between Python2 and Pyt
3 min read
SQL using Python | Set 3 (Handling large data)
It is recommended to go through SQL using Python | Set 1 and SQL using Python and SQLite | Set 2 In the previous articles the records of the database were limited to small size and single tuple. This article will explain how to write & fetch large data from the database using module SQLite3 covering all exceptions. A simple way is to execute th
4 min read
Handling PostgreSQL BLOB data in Python
In this article, we will learn how to Handle PostgreSQL BLOB data in Python. BLOB is a Binary large object (BLOB) is a data type that can store any binary data.To store BLOB data in a PostgreSQL database, we need to use the Binary Large Object (BLOB) data type.By using the Binary Large Object (BLOB) data type, we can store any binary data in a Post
5 min read