Open In App

Python – Remove last element from dictionary

Last Updated : 18 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a dictionary, the task is to remove the last occurring element, i.e. the last key-value pair in the dictionary. 

Example:

Input: {1: 'Geeks', 2: 'For', 3: 'Geeks'}
Output:{1: 'Geeks', 2: 'For'}

Method 1: Using popitem() method

Python dictionary popitem() method removes one key, value pair as a two-item tuple and modifies the removes the last key from the dictionary.

Python3




dic = {1: "one", 2: "two", 3: "three"}
dic.popitem()
print(dic)


Output:

{1: 'one', 2: 'two'}

Time complexity: O(1) on average for the “popitem” method. This is because the “popitem” method retrieves and removes an arbitrary item from the dictionary in constant time.
Auxiliary space: O(1), as removing an item from the dictionary only requires a constant amount of memory regardless of the size of the dictionary. 

Explanation: Here, we are using the built-in popitem() method to remove the last element in the dictionary.

Method 2: Using Python Dict pop() Method

Here, we get the lat key in the dictionary and remove the last key from the dictionary using .pop() method of dictionary

Python3




dic = {1: "one", 2: "two", 3: "three"}
# get the last key to remove from dict
last_key = list(dic)[-1]
# remove the last key using .pop() method
removed_tuple = dic.pop(last_key)
# modified dictionary
print(dic)


Output:

{1: 'one', 2: 'two'}

Time complexity: O(1) – as the time taken to retrieve the last key and remove it from the dictionary using the .pop() method is constant and does not increase with the size of the dictionary.

Auxiliary space complexity: O(1) – as the space used to store the removed key-value tuple is constant and does not increase with the size of the dictionary.

Method 3: Using items() + dict comprehension to Remove the last Key from a Dictionary

Python3




dic1={1:"one", 2:"two", 3:"three"}
l_key = list(dic1.keys())[-1]
dic2 = {key: val for key,
            val in dic1.items() if key != l_key}
# Printing dictionary after removal
print("The dictionary after removing element is :", dic2)


Output:

The dictionary after removing element is : {1: 'one', 2: 'two'}

Time complexity: O(n), where n is the number of items in the dictionary.
Auxiliary space: O(n), where n is the number of items in the dictionary, 

Method 4: Using del keyword in Python

Here we are using the Python del keyword to remove the last key from a dictionary. In this the original dictionary is modified.

Python3




dic = {1: "one", 2: "two", 3: "three"}
# get the last key to remove from dict
last_key = list(dic)[-1]
# remove the last key using del method
del dic[last_key]
# modified dictionary
print(dic)


Output:

{1: 'one', 2: 'two'}

Time complexity: O(1) for the deletion operation and O(n) for creating a list of dictionary keys, where n is the number of keys in the dictionary. 
Auxiliary space: O(n) as well, due to the creation of the list of keys.

Method 5: Creating a new dictionary by iterating through the original dictionary 

Creating a new dictionary by iterating through the original dictionary and skipping the last key-value pair. This can be done using a for loop. For example:

Python3




dic1={1:"one", 2:"two", 3:"three"}
# create a new dictionary
dic2 = {}
# iterate through the original dictionary and skip the last key-value pair
for key, val in dic1.items():
    if key != list(dic1)[-1]:
        dic2[key] = val
# Printing dictionary after removal
print("The dictionary after removing element is :", dic2)
#This code is contributed by Edula Vinay Kumar Reddy


Output:

The dictionary after removing the element is: {1: 'one', 2: 'two'}

Time complexity: O(n), where n is the number of elements in the dictionary, 
Auxiliary Space: O(n).

Here we have seen some of the possible methods of deleting the items from the dictionary.

Method 6 : Using keys() and slicing method

Python3




dic1={1:"one", 2:"two", 3:"three"}
# create a new dictionary
dic2 = {}
# iterate through the original dictionary and skip the last key-value pair
x=list(dic1.keys())
for i in x[:len(x)-1]:
    dic2[i]=dic1[i]
# Printing dictionary after removal
print("The dictionary after removing element is :", dic2)


Output

The dictionary after removing element is : {1: 'one', 2: 'two'}

Time complexity: O(n), where n is the number of elements in the dictionary
Auxiliary Space: O(n)

Method 7:

In this implementation, we use the items() method to get a list of key-value pairs from the dictionary, then we use negative indexing to get the last key-value pair in the list. Then we use the key of the last pair to remove the corresponding element from the dictionary using the pop() method.

Python3




# Function to remove the last occurring element
def remove_last_occurrence(dictionary):
    # Get the last key-value pair using negative indexing
    last_pair = list(dictionary.items())[-1]
    # Use the key to remove the element from the dictionary
    dictionary.pop(last_pair[0])
    return dictionary
 
 
# Test the function
my_dict = {1: "one", 2: "two", 3: "three"}
print(remove_last_occurrence(my_dict))


Output

{1: 'one', 2: 'two'}

Time Complexity: O(n), where n is the number of elements in the dictionary
Auxiliary Space: O(n), as well, as we are creating a list of key-value pairs from the dictionary and storing it in memory.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads