Delete dictionary by value python

There're a lot of nice answers, but I want to emphasize one thing.

You can use both dict.pop[] method and a more generic del statement to remove items from a dictionary. They both mutate the original dictionary, so you need to make a copy [see details below].

And both of them will raise a KeyError if the key you're providing to them is not present in the dictionary:

key_to_remove = "c"
d = {"a": 1, "b": 2}
del d[key_to_remove]  # Raises `KeyError: 'c'`

and

key_to_remove = "c"
d = {"a": 1, "b": 2}
d.pop[key_to_remove]  # Raises `KeyError: 'c'`

You have to take care of this:

by capturing the exception:

key_to_remove = "c"
d = {"a": 1, "b": 2}
try:
    del d[key_to_remove]
except KeyError as ex:
    print["No such key: '%s'" % ex.message]

and

key_to_remove = "c"
d = {"a": 1, "b": 2}
try:
    d.pop[key_to_remove]
except KeyError as ex:
    print["No such key: '%s'" % ex.message]

by performing a check:

key_to_remove = "c"
d = {"a": 1, "b": 2}
if key_to_remove in d:
    del d[key_to_remove]

and

key_to_remove = "c"
d = {"a": 1, "b": 2}
if key_to_remove in d:
    d.pop[key_to_remove]

but with pop[] there's also a much more concise way - provide the default return value:

key_to_remove = "c"
d = {"a": 1, "b": 2}
d.pop[key_to_remove, None]  # No `KeyError` here

Unless you use pop[] to get the value of a key being removed you may provide anything, not necessary None. Though it might be that using del with in check is slightly faster due to pop[] being a function with its own complications causing overhead. Usually it's not the case, so pop[] with default value is good enough.

As for the main question, you'll have to make a copy of your dictionary, to save the original dictionary and have a new one without the key being removed.

Some other people here suggest making a full [deep] copy with copy.deepcopy[], which might be an overkill, a "normal" [shallow] copy, using copy.copy[] or dict.copy[], might be enough. The dictionary keeps a reference to the object as a value for a key. So when you remove a key from a dictionary this reference is removed, not the object being referenced. The object itself may be removed later automatically by the garbage collector, if there're no other references for it in the memory. Making a deep copy requires more calculations compared to shallow copy, so it decreases code performance by making the copy, wasting memory and providing more work to the GC, sometimes shallow copy is enough.

However, if you have mutable objects as dictionary values and plan to modify them later in the returned dictionary without the key, you have to make a deep copy.

With shallow copy:

def get_dict_wo_key[dictionary, key]:
    """Returns a **shallow** copy of the dictionary without a key."""
    _dict = dictionary.copy[]
    _dict.pop[key, None]
    return _dict


d = {"a": [1, 2, 3], "b": 2, "c": 3}
key_to_remove = "c"

new_d = get_dict_wo_key[d, key_to_remove]
print[d]  # {"a": [1, 2, 3], "b": 2, "c": 3}
print[new_d]  # {"a": [1, 2, 3], "b": 2}
new_d["a"].append[100]
print[d]  # {"a": [1, 2, 3, 100], "b": 2, "c": 3}
print[new_d]  # {"a": [1, 2, 3, 100], "b": 2}
new_d["b"] = 2222
print[d]  # {"a": [1, 2, 3, 100], "b": 2, "c": 3}
print[new_d]  # {"a": [1, 2, 3, 100], "b": 2222}

With deep copy:

from copy import deepcopy


def get_dict_wo_key[dictionary, key]:
    """Returns a **deep** copy of the dictionary without a key."""
    _dict = deepcopy[dictionary]
    _dict.pop[key, None]
    return _dict


d = {"a": [1, 2, 3], "b": 2, "c": 3}
key_to_remove = "c"

new_d = get_dict_wo_key[d, key_to_remove]
print[d]  # {"a": [1, 2, 3], "b": 2, "c": 3}
print[new_d]  # {"a": [1, 2, 3], "b": 2}
new_d["a"].append[100]
print[d]  # {"a": [1, 2, 3], "b": 2, "c": 3}
print[new_d]  # {"a": [1, 2, 3, 100], "b": 2}
new_d["b"] = 2222
print[d]  # {"a": [1, 2, 3], "b": 2, "c": 3}
print[new_d]  # {"a": [1, 2, 3, 100], "b": 2222}

This article describes how to remove an item [element] from a dictionary dict in Python.

  • Remove all items from a dictionary: clear[]
  • Remove an item by a key and return a value: pop[]
  • Remove an item and return a key and value: popitem[]
  • Remove an item by a key from a dictionary: del
  • Remove items that meet the condition: Dictionary comprehensions

See the following article for how to add items to a dictionary.

  • Merge multiple dictionaries and add items to a dictionary in Python

Remove all items from a dictionary: clear[]

The clear[] method removes all items from a dictionary and makes it empty.

d = {'k1': 1, 'k2': 2, 'k3': 3}

d.clear[]
print[d]
# {}

Remove an item by a key and return a value: pop[]

By specifying a key to the pop[] method, the item is removed and its value is returned.

d = {'k1': 1, 'k2': 2, 'k3': 3}

removed_value = d.pop['k1']
print[d]
# {'k2': 2, 'k3': 3}

print[removed_value]
# 1

By default, specifying a non-existent key raises KeyError.

d = {'k1': 1, 'k2': 2, 'k3': 3}

# removed_value = d.pop['k4']
# print[d]
# KeyError: 'k4'

If the second argument is specified, its value is returned if the key does not exist. The dictionary itself remains unchanged.

d = {'k1': 1, 'k2': 2, 'k3': 3}

removed_value = d.pop['k4', None]
print[d]
# {'k1': 1, 'k2': 2, 'k3': 3}

print[removed_value]
# None

Remove an item and return a key and value: popitem[]

The popitem[] method removes an item from a dictionary and returns a tuple of its key and value [key, value]. You cannot specify which item to remove.

An error KeyError is raised for an empty dictionary.

d = {'k1': 1, 'k2': 2}

k, v = d.popitem[]
print[k]
print[v]
print[d]
# k2
# 2
# {'k1': 1}

k, v = d.popitem[]
print[k]
print[v]
print[d]
# k1
# 1
# {}

# k, v = d.popitem[]
# KeyError: 'popitem[]: dictionary is empty'

Remove an item by a key from a dictionary: del

You can also use the del statement to delete an item from a dictionary.

d = {'k1': 1, 'k2': 2, 'k3': 3}

del d['k2']
print[d]
# {'k1': 1, 'k3': 3}

You can specify and remove multiple items.

d = {'k1': 1, 'k2': 2, 'k3': 3}

del d['k1'], d['k3']
print[d]
# {'k2': 2}

If a non-existent key is specified, the error KeyError is raised.

d = {'k1': 1, 'k2': 2, 'k3': 3}

# del d['k4']
# print[d]
# KeyError: 'k4'

Remove items that meet the condition: Dictionary comprehensions

To remove items that satisfy the conditions from a dictionary, use dictionary comprehensions, the dictionary version of list comprehensions.

  • List comprehensions in Python

"Removing items that meet the condition" is the same as "extracting items that do not meet the condition".

For example, to remove items with an odd value, you can extract items with an even value. The same applies to the opposite case.

d = {'apple': 1, 'banana': 10, 'orange': 100}

dc = {k: v for k, v in d.items[] if v % 2 == 0}
print[dc]
# {'banana': 10, 'orange': 100}

dc = {k: v for k, v in d.items[] if v % 2 == 1}
print[dc]
# {'apple': 1}

The items[] method of dict is used to extract keys and values.

  • Iterate dictionary [key and value] with for loop in Python

It is also possible to specify conditions for keys.

dc = {k: v for k, v in d.items[] if k.endswith['e']}
print[dc]
# {'apple': 1, 'orange': 100}

dc = {k: v for k, v in d.items[] if not k.endswith['e']}
print[dc]
# {'banana': 10}

You can also use and and or to specify multiple conditions.

  • Boolean operators in Python [and, or, not]

dc = {k: v for k, v in d.items[] if v % 2 == 0 and k.endswith['e']}
print[dc]
# {'orange': 100}

How do you delete a specific value from a dictionary in Python?

You can use the following methods to remove items from a dictionary in Python:.
The del keyword..
The clear[] method..
The pop[] method..
The popitem[] method..

How do you remove a specific value from a dictionary?

There are several ways to remove a key: value pair from a dictionary..
Using del. The del keyword deletes a key: value pair from a dictionary. ... .
Using popitem[] The in-built function popitem[] deletes the last key: value pair in a dictionary. ... .
Using pop[].

How do you delete a whole dictionary in Python?

The clear[] method removes all items from the dictionary..
Syntax: dict.clear[].
Parameters: The clear[] method doesn't take any parameters..
Returns: The clear[] method doesn't return any value..
Examples: Input : d = {1: "geeks", 2: "for"} d.clear[] Output : d = {}.
Error: ... .
Output: text = {}.

How do you delete and remove an element from a dictionary Python?

Python Program to Remove a Key from a Dictionary.
Declare and initialize a dictionary to have some key-value pairs..
Take a key from the user and store it in a variable..
Using an if statement and the in operator, check if the key is present in the dictionary..
If it is present, delete the key-value pair..

Chủ Đề