Open In App

Python - Remove Dictionary if Given Key's Value is N

Last Updated : 01 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a dictionary we need to remove key if the given value of key is N. For example, we are given a dictionary d = {'a': 1, 'b': 2, 'c': 3} we need to remove the key if the value is N so that the output becomes {'a': 1, 'c': 3}. We can use methods like del, pop and various other methods like dictionary comprehension.

Using del

Using del we can remove a dictionary entry by specifying the key associated with value we want to delete. We first check if key exists and its value matches target value before using del to remove key-value pair from dictionary.

Python
d = {'a': 1, 'b': 2, 'c': 3}
key_r = 'b'
val_r = 2

# Check and delete if the condition is met
if d.get(key_r) == val_r:
    del d[key_r]

print(d)

Output
{'a': 1, 'c': 3}

Explanation:

  • Code checks if value associated with the specified key (key_r) matches the target value (val_r) using d.get(key_r).
  • If condition is true del statement removes the key-value pair from dictionary.

Using pop()

pop() method removes a key-value pair from the dictionary if key's value matches specified value, and returns the value. This deletes pair from dictionary.

Python
d = {'a': 1, 'b': 2, 'c': 3}
key_r = 'b'
val_r = 2

# Use pop() to remove the key if the value matches
if d.get(key_r) == val_r:
    d.pop(key_r)

print(d)

Explanation:

  • Code checks if value associated with specified key ('b') matches the given value (2).
  • If condition is met pop() method is used to remove key-value pair from dictionary and return value.

Using Dictionary Comprehension

Code creates a new dictionary excluding the key-value pair where value matches 2 using dictionary comprehension. Only pairs with different values are retained in new dictionary.

Python
d = {'a': 1, 'b': 2, 'c': 3}
key_r = 'b'
val_r = 2

# Create a new dictionary excluding the key-value pair
d = {key: value for key, value in d.items() if not (key == key_r and value == val_r)}

print(d)

Output
{'a': 1, 'c': 3}

Explanation:

  • Code uses dictionary comprehension to iterate over the original dictionary and check if the key-value pair matches given key (key_r) and value (val_r).
  • If pair matches it is excluded from new dictionary effectively removing key-value pair 'b': 2.

Next Article
Practice Tags :

Similar Reads