Open In App

Python – Remove Kth key from dictionary

Improve
Improve
Like Article
Like
Save
Share
Report

Many times, while working with Python, we can have a situation in which we require to remove the Kth key of the dictionary. This is useful for Python version 3.8 +, where key ordering is similar to the insertion order. Let’s discuss certain ways in which this task can be performed.

Examples:

Input : test_dict = {“Gfg” : 20, “is” : 36, “best” : 100, “for” : 17, “geeks” : 1} , K = 4 
Output : {‘Gfg’: 20, ‘is’: 36, ‘best’ : 100, ‘geeks’: 1} 
Explanation : 4th index, for is removed.

Input : test_dict = {“Gfg” : 20, “is” : 36, “best” : 100, “for” : 17, “geeks” : 1} , K = 2 
Output : {‘Gfg’: 20, ‘best’ : 100, ‘for’ : 17, ‘geeks’: 1} 
Explanation : 2nd index, ‘is’ is removed. 

Method #1 : Using del + loop

This is one of the ways in which this task can be performed. In this, we iterate for the keys, along with the counter, when we get the key, we perform its removal. This performs inplace removal.

Python3




# Python3 code to demonstrate working of
# Remove Kth key from dictionary
# Using loop
 
# initializing dictionary
test_dict = {"Gfg" : 20, "is" : 36, "best" : 100,
             "for" : 17, "geeks" : 1}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing size
K = 3
 
cnt = 0
for key in test_dict:
    cnt += 1
     
    # delete key if counter is equal to K
    if cnt == K:
        del test_dict[key]
        break
     
# printing result
print("Required dictionary after removal : " + str(test_dict))


Output:

The original dictionary is : {‘Gfg’: 20, ‘is’: 36, ‘best’: 100, ‘for’: 17, ‘geeks’: 1}
Required dictionary after removal : {‘Gfg’: 20, ‘is’: 36, ‘for’: 17, ‘geeks’: 1}

Time Complexity: O(n), where n is number of key-value pairs in the dictionary.
Auxiliary Space: O(1)

Method #2 : Using keys() + dictionary comprehension

This is yet another way in which this task can be performed. In this, we recreate the dictionary without including the required key, by extracting key to be removed using keys(), we include all keys except required into new dictionary.

Python3




# Python3 code to demonstrate working of
# Remove Kth key from dictionary
# Using Remove Kth key from dictionary
 
# initializing dictionary
test_dict = {"Gfg" : 20, "is" : 36, "best" : 100,
             "for" : 17, "geeks" : 1}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing size
K = 3
 
# dictionary comprehension remakes dictionary,
# rather than removing
res = {key: val for key, val in test_dict.items()
       if key != list(test_dict.keys())[K - 1]}
     
# printing result
print("Required dictionary after removal : " + str(res))


Output:

The original dictionary is : {‘Gfg’: 20, ‘is’: 36, ‘best’: 100, ‘for’: 17, ‘geeks’: 1}
Required dictionary after removal : {‘Gfg’: 20, ‘is’: 36, ‘for’: 17, ‘geeks’: 1}

Method #3 : Using pop() method

Use the pop() method to remove the item with the key at the specified index from the input dictionary.

Step-by-step approach:

  • Get the key at the specified index k from the input dictionary.
  • Use the pop() method to remove the item with the key k from the input dictionary
  • Return the updated dictionary.

Python3




def remove_kth_key_pop(test_dict, k):#defie testdict and k
    test_dict.pop(list(test_dict.keys())[k-1])#using pop to remove key value
    return test_dict#return result
#inputs
test_dict={'Gfg': 20, 'is': 36, 'best': 100, 'for': 17, 'geeks': 1}
k = 4
print(remove_kth_key_pop(test_dict, k))#print result


Output

{'Gfg': 20, 'is': 36, 'best': 100, 'geeks': 1}

Time Complexity: O(k) + O(1) = O(k). Getting the key at the specified index k takes O(k) time as we need to iterate over the keys of the dictionary to get the kth key. Using the pop() method takes O(1) time on average to remove the item with the specified key from the dictionary.
Auxiliary Space: O(1), This approach uses constant extra space to store the key at the specified index k.

Method #4: Using dictionary comprehension + enumerate

This method works by using the enumerate() function to generate a sequence of (index, (key, value)) tuples for each item in the dictionary. It then uses dictionary comprehension to construct a new dictionary by iterating over this sequence and including only those items whose index is not equal to K-1 (i.e., the Kth item).

Python3




# Python3 code to demonstrate working of
# Remove Kth key from dictionary
# Using dictionary comprehension + enumerate
 
# initializing dictionary
test_dict = {"Gfg" : 20, "is" : 36, "best" : 100,
             "for" : 17, "geeks" : 1}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing size
K = 3
 
# using dictionary comprehension + enumerate to remove Kth key
test_dict = {key: val for i, (key, val) in enumerate(test_dict.items()) if i != K-1}
 
# printing result
print("Required dictionary after removal : " + str(test_dict))


Output

The original dictionary is : {'Gfg': 20, 'is': 36, 'best': 100, 'for': 17, 'geeks': 1}
Required dictionary after removal : {'Gfg': 20, 'is': 36, 'for': 17, 'geeks': 1}

Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), because it creates a new dictionary with at most n-1 key-value pairs (if the Kth key is not found), and this new dictionary is stored in memory.

Method #5: Using dictionary comprehension + conditional statement

  • Start by initializing the dictionary and the value of K.
  • Create a new dictionary comprehension that iterates over each key-value pair in the original dictionary.
  • Include a conditional statement that checks if the current iteration is equal to the Kth key in the dictionary.
  • If the condition is false, add the key-value pair to the new dictionary.
  • Return the new dictionary.

Python3




# Python3 code to demonstrate working of
# Remove Kth key from dictionary
# Using dictionary comprehension + conditional statement
 
# initializing dictionary
test_dict = {"Gfg" : 20, "is" : 36, "best" : 100,
             "for" : 17, "geeks" : 1}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing size
K = 3
 
# using dictionary comprehension and conditional statement to remove Kth key
new_dict = {key: val for i, (key, val) in enumerate(test_dict.items()) if i != K-1}
 
# printing result
print("Required dictionary after removal : " + str(new_dict))


Output

The original dictionary is : {'Gfg': 20, 'is': 36, 'best': 100, 'for': 17, 'geeks': 1}
Required dictionary after removal : {'Gfg': 20, 'is': 36, 'for': 17, 'geeks': 1}

Time Complexity: O(N) where N is the number of key-value pairs in the dictionary since we need to iterate through each key-value pair once.
Auxiliary Space: O(N) where N is the number of key-value pairs in the dictionary since we are creating a new dictionary to store the key-value pairs.



Last Updated : 16 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads