View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
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:
As we are not passing any parameters there is no chance for any error.
text
=
{
1
:
"geeks"
,
2
:
"for"
}
text.clear[]
print
[
'text ='
, text]
Output:
text = {}
How is it different from assigning {} to a dictionary?
Please refer the below code to see the difference. When we assign {} to a dictionary, a new empty dictionary is
created and assigned to the reference. But when we do clear on a dictionary reference, the actual dictionary content is removed, so all references referring to the dictionary become empty.
text1
=
{
1
:
"geeks"
,
2
:
"for"
}
text2
=
text1
text1.clear[]
print
[
'After removing items using clear[]'
]
print
[
'text1 ='
, text1]
print
[
'text2 ='
, text2]
text1
=
{
1
:
"one"
,
2
:
"two"
}
text2
=
text1
text1
=
{}
print
[
'After removing items by assigning {}'
]
print
[
'text1 ='
, text1]
print
[
'text2 ='
, text2]
Output:
After removing items using clear[] text1 = {} text2 = {} After removing items by assigning {} text1 = {} text2 = {1: 'one', 2: 'two'}
Removing Items from a Dictionary
There are several methods to remove items from a dictionary:
Example
The pop[]
method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop["model"]
print[thisdict]
Try it Yourself »
Example
The popitem[]
method removes the last inserted item [in versions before 3.7, a random item is removed instead]:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem[]
print[thisdict]
Try it Yourself »
Example
The
del
keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print[thisdict]
Try it Yourself »
Example
The del
keyword can also delete the dictionary completely:
thisdict = {
"brand":
"Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print[thisdict] #this will cause an error because "thisdict" no longer exists.
Try it Yourself »
Example
The clear[]
keyword empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year":
1964
}
thisdict.clear[]
print[thisdict]
Try it Yourself »
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}