VOOZH about

URL: https://www.geeksforgeeks.org/python/python-remove-item-from-dictionary-when-key-is-unknown/

⇱ Python - Remove item from dictionary when key is unknown - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python - Remove item from dictionary when key is unknown

Last Updated : 11 Jul, 2025

We are given a dictionary we need to remove the item or the value of key which is unknown. For example, we are given a dictionary a = {'a': 10, 'b': 20, 'c': 30} we need to remove the key 'b' so that the output dictionary becomes like {'a': 10, 'c': 30} . To do this we can use various method and approaches for python.

Using a Loop and Condition

In the loop-and-condition method, we iterate through the dictionary to identify the key that satisfies a specific condition. Once found, the key is removed using the del statement.


Output
{'a': 10, 'c': 30}

Explanation:

  • loop iterates over the dictionary, and the condition checks if the current key-value pair satisfies the criteria (v == 20); if found, the key is stored and the loop exits.
  • If a key is identified, it is deleted from the dictionary using the del statement, updating the dictionary.

Using Dictionary Comprehension

Dictionary comprehension creates a new dictionary by excluding items that meet the condition, such as removing entries where value equals 20.


Output
{'a': 10, 'c': 30}

Explanation:

  • A lambda function c is defined to match key-value pairs where the value equals 20, and dictionary comprehension is used to filter out such pairs.
  • Comprehension creates a new dictionary f, including only the key-value pairs where the value is not 20, resulting in {'a': 10, 'c': 30}

Using next()

next() function is used with a generator expression to find the first key that satisfies the condition (e.g., value equals 20). If a matching key is found, it is removed from the dictionary using del.


Output
{'a': 10, 'c': 30}

Explanation:

  • next() function with a generator expression searches for the first key-value pair that meets the condition (value == 20), returning the key if found, or None if not.
  • If a matching key is found, it is deleted from the dictionary using del, updating the dictionary.

Using pop() with a Condition

pop() method can be used to remove a key-value pair from the dictionary if a key that satisfies a condition is found. The condition is checked using a generator expression, and pop() removes the corresponding key-value pair if a match is found.


Output
{'a': 10, 'c': 30}

Explanation:

  • next() function with a generator expression is used to locate the first key-value pair where the value is 20, returning the key if found, or None if not.
  • If a key is found, the pop() method removes that key-value pair from the dictionary, updating the dictionary accordingly
Comment