Remove Kth Key from Dictionary - Python
Last Updated :
29 Jan, 2025
We are given a dictionary we need to remove Kth key from the dictionary. For example, we are given a dictionary d = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'} we need to remove the key2 so that the output should be {'key1': 'value1', 'key3': 'value3', 'key4': 'value4'}.
Using del
del statement removes a specified key-value pair from a dictionary by directly referencing the key.
Python
d = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'}
K = 'key2'
# Using del
del d[K] # Removes 'key2' from the dictionary
print(f"After using del: {d}")
OutputAfter using del: {'key1': 'value1', 'key3': 'value3', 'key4': 'value4'}
Explanation:
del
statement is used to remove the key-value pair associated with the key 'key2'
from dictionary d
which results in removal of that entry.- After using
del d[K]
dictionary d
is updated and key 'key2'
is no longer present in it.
Using pop()
pop() method can be used to remove the Kth key from a dictionary by first extracting the key at the desired index using list. Then pop() removes this key and returns its value ensuring safe deletion without modifying the dictionary during iteration.
Python
d = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'}
K = 'key2'
# Using pop()
rem_val = d.pop(K) # Removes 'key2' and returns its value
print(f"After using pop: {d}, Removed Value: {rem_val}")
OutputAfter using pop: {'key1': 'value1', 'key3': 'value3', 'key4': 'value4'}, Removed Value: value2
Explanation:
pop()
method is used to remove the key-value pair for 'key2'
from dictionary d
and return its value ('value2'
), which is stored in variable rem_val
.- After using
pop()
dictionary d
is updated with 'key2'
removed and removed value ('value2'
) is printed.
Using Dictionary Comprehension
Using dictionary comprehension we can create a new dictionary that excludes the key 'key2'
by iterating over the original dictionary and filtering out the pair where key matches 'key2'
.
Python
d = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'}
K='key1'
# Using dict comprehension
d = {key: value for key, value in d.items() if key != K} # Creates a new dictionary excluding 'key2'
print(f"After using dict comprehension: {d}")
OutputAfter using dict comprehension: {'key2': 'value2', 'key3': 'value3', 'key4': 'value4'}
Explanation:
- Dictionary comprehension iterates over the key-value pairs in the original dictionary and includes only those pairs where the key is not equal to
'key1'
. - This results in a new dictionary that excludes the key
'key1'
effectively removing it from original dictionary
Using filter()
Using the filter
()
function we can filter out the key-value pairs where the key matches 'key1'
by applying a condition that checks if the key is not equal to 'key1'
. This method returns an iterable which is then converted back into a dictionary effectively removing the key 'key1'
from the original dictionary.
Python
# Reset the dictionary for the next example
d = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'}
K='key2'
# Using filter()
d = dict(filter(lambda item: item[0] != K, d.items())) # Filters out 'key2'
print(f"After using filter: {d}")
OutputAfter using filter: {'key1': 'value1', 'key3': 'value3', 'key4': 'value4'}
Explanation:
- filter() function is used with a lambda to exclude key-value pairs where the key is equal to 'key1' lambda function checks each dictionary item and returns True for keys that are not 'key1', effectively filtering them out.
- Filtered result is converted back into a dictionary using dict(), leaving the key 'key1' removed from the original dictionary.
Similar Reads
Python - Remove Multiple Keys from Dictionary We are given a dictionary and our task is to remove multiple keys from the dictionary. For example, consider a dictionary d = {'a': 1, 'b': 2, 'c': 3, 'd': 4} where we want to remove the keys 'b' and 'd', then the output will be {'a': 1, 'c': 3}. Let's explore different methods to remove multiple ke
3 min read
Python - Remove Item from Dictionary There are situations where we might want to remove a specific key-value pair from a dictionary. For example, consider the dictionary d = {'x': 10, 'y': 20, 'z': 30}. If we need to remove the key 'y', there are multiple ways to achieve this. Let's discuss several methods to remove an item from a dict
3 min read
Python Remove Item from Dictionary by Key Dictionaries in Python store data as key-value pairs. Often, we need to remove a specific key-value pair to modify or clean the dictionary. For instance, consider the dictionary d = {'a': 1, 'b': 2, 'c': 3}; we might want to remove the key 'b'. Let's explore different methods to achieve this.Using d
3 min read
Remove Spaces from Dictionary Keys - Python Sometimes, the keys in a dictionary may contain spaces, which can create issues while accessing or processing the data. For example, consider the dictionary d = {'first name': 'Nikki', 'last name': 'Smith'}. We may want to remove spaces from the keys to standardize the dictionary, resulting in {'fir
3 min read
Python Remove Key from Dictionary if Exists We are given a dictionary and a key and our task is to remove the key from the dictionary if it exists. For example, d = {"a": 10, "b": 20, "c": 30} and key to remove is "b" then output will be {"a": 10, "c": 30}.Using pop() pop() method allows us to remove a key from a dictionary while specifying a
2 min read
Python - Remove Top level from Dictionary Sometimes, while working with Python Dictionaries, we can have nesting of dictionaries, with each key being single values dictionary. In this we need to remove the top level of dictionary. This can have application in data preprocessing. Lets discuss certain ways in which this task can be performed.
3 min read
Python - Remove K valued key from Nested Dictionary We are given a nested dictionary we need to remove K valued key. For example, we are given a nested dictionary d = { "a": 1, "b": {"c": 2,"d": {"e": 3,"f": 1},"g": 1},"h": [1, {"i": 1, "j": 4}]} we need to remove K valued key ( in our case we took k value as 1 ) from it so that the output should be
3 min read
Remove a Key from a Python Dictionary Using loop Sometimes, we need to remove specific keys while iterating through the dictionary. For example, consider the dictionary d = {'a': 1, 'b': 2, 'c': 3}. If we want to remove the key 'b', we need to handle this efficiently, especially to avoid issues like modifying the dictionary during iteration. Let's
2 min read
Python Remove Dictionary Item Sometimes, we may need to remove a specific item from a dictionary to update its structure. For example, consider the dictionary d = {'x': 100, 'y': 200, 'z': 300}. If we want to remove the item associated with the key 'y', several methods can help achieve this. Letâs explore these methods.Using pop
2 min read