Python - Remove item from dictionary when key is unknown Last Updated : 25 Jan, 2025 Comments Improve Suggest changes Like Article Like Report 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 ConditionIn 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. Python a = {'a': 10, 'b': 20, 'c': 30} # Define a condition function to match key-value pairs condition = lambda k, v: v == 20 # Matches if the value is 20 # Initialize a variable to store the key to be removed k = None # Iterate over the dictionary items (key-value pairs) for k, v in a.items(): if condition(k, v): # Check if the current key-value pair satisfies the condition k = k # Store the key to be removed break # Exit the loop once the key is found # Remove the key if one was identified if k: del a[k] # Delete the key-value pair from the dictionary print(a) 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 ComprehensionDictionary comprehension creates a new dictionary by excluding items that meet the condition, such as removing entries where value equals 20. Python a = {'a': 10, 'b': 20, 'c': 30} # Define a condition function to match key-value pairs c = lambda k, v: v == 20 # Matches if the value is 20 # Use dictionary comprehension to create a new dictionary # Exclude key-value pairs that satisfy the condition f = {k: v for k, v in a.items() if not c(k, v)} print(f) 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. Python # Initialize the dictionary a = {'a': 10, 'b': 20, 'c': 30} # Define a condition function to match key-value pairs c = lambda k, v: v == 20 # Matches if the value is 20 # Use next() with a generator expression to find the first key that matches the condition # If no key is found, None is returned k = next((k for k, v in a.items() if c(k, v)), None) # If a key is found, remove it from the dictionary if k: del a[k] print(a) 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 Conditionpop() 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. Python a = {'a': 10, 'b': 20, 'c': 30} # Define a condition function to match key-value pairs c = lambda key, val: val == 20 # Matches if the value is 20 # Use next() with a generator expression to find the first key that matches the condition # If no key is found, None is returned k = next((key for key, val in a.items() if c(key, val)), None) # If a key is found, remove it from the dictionary using pop() if k: a.pop(k) print(a) 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 More infoAdvertise with us Next Article Python - Remove item from dictionary when key is unknown G garg_ak0109 Follow Improve Article Tags : Python python-dict Python dictionary-programs Practice Tags : pythonpython-dict Similar Reads Calculating the Product of List Lengths in a Dictionary - Python The task of calculating the product of the lengths of lists in a dictionary involves iterating over the dictionaryâs values, which are lists and determining the length of each list. These lengths are then multiplied together to get a single result. For example, if d = {'A': [1, 2, 3], 'B': [4, 5], ' 3 min read Python - Access Dictionary items A dictionary in Python is a useful way to store data in pairs, where each key is connected to a value. To access an item in the dictionary, refer to its key name inside square brackets.Example:Pythona = {"Geeks": 3, "for": 2, "geeks": 1} #Access the value assosiated with "geeks" x = a["geeks"] print 3 min read Dictionary items in value range in Python In this article, we will explore different methods to extract dictionary items within a specific value range. The simplest approach involves using a loop.Using LoopThe idea is to iterate through dictionary using loop (for loop) and check each value against the given range and storing matching items 2 min read Ways to change keys in dictionary - Python Given a dictionary, the task is to change the key based on the requirement. Let's see different methods we can do this task in Python. Example:Pythond = {'nikhil': 1, 'manjeet': 10, 'Amit': 15} val = d.pop('Amit') d['Suraj'] = val print(d)Output{'nikhil': 1, 'manjeet': 10, 'Suraj': 15} Explanation:T 2 min read Python Program to Swap dictionary item's position Given a Dictionary, the task is to write a python program to swap positions of dictionary items. The code given below takes two indices and swap values at those indices. Input : test_dict = {'Gfg' : 4, 'is' : 1, 'best' : 8, 'for' : 10, 'geeks' : 9}, i, j = 1, 3 Output : {'Gfg': 4, 'for': 10, 'best': 4 min read Merging or Concatenating two Dictionaries in Python Combining two dictionaries is a common task when working with Python, especially when we need to consolidate data from multiple sources or update existing records. For example, we may have one dictionary containing user information and another with additional details and we'd like to merge them into 2 min read How to Compare Two Dictionaries in Python In this article, we will discuss how to compare two dictionaries in Python. The simplest way to compare two dictionaries for equality is by using the == operator.Using == operatorThis operator checks if both dictionaries have the same keys and values.Pythond1 = {'a': 1, 'b': 2} d2 = {'a': 1, 'b': 2} 2 min read Python Dictionary Comprehension Like List Comprehension, Python allows dictionary comprehensions. We can create dictionaries using simple expressions. A dictionary comprehension takes the form {key: value for (key, value) in iterable}Python Dictionary Comprehension ExampleHere we have two lists named keys and value and we are iter 4 min read How to Add Values to Dictionary in Python The task of adding values to a dictionary in Python involves inserting new key-value pairs or modifying existing ones. A dictionary stores data in key-value pairs, where each key must be unique. Adding values allows us to expand or update the dictionary's contents, enabling dynamic manipulation of d 3 min read Add new keys to a dictionary in Python In this article, we will explore various methods to add new keys to a dictionary in Python. Let's explore them with examples:Using Assignment Operator (=)The simplest way to add a new key is by using assignment operator (=).Pythond = {"a": 1, "b": 2} d["c"] = 3 print(d)Output{'a': 1, 'b': 2, 'c': 3} 2 min read Like