dict.clear()
Deletes every key and value from a dictionary in place. Every variable that refers to the same dictionary sees it empty.
dict.clear()clear() empties a dictionary. Afterwards it is the same object as before, just with no entries, like {}.
Use it to reset a cache, a counter or a set of results that other parts of your program also hold on to.
The difference from d = {} is the same as for lists: clear() empties the one shared dictionary, while d = {} only points the name d at a new, empty dictionary and leaves the old one (and anyone else using it) untouched.
Return value
Nothing (None). The dictionary is changed in place.
Examples
1Empty a dictionary
cart = {"apple": 2, "bread": 1}
cart.clear()
print(cart)
print(len(cart)){}
02clear() vs a new empty dictionary
cache = {"a": 1}
alias = cache
cache.clear()
print(alias)
scores = {"b": 2}
other = scores
scores = {}
print(other){}
{'b': 2}3Reset counts between rounds
tally = {}
for rnd, votes in enumerate([["yes", "no", "yes"], ["no"]], start=1):
tally.clear()
for v in votes:
tally[v] = tally.get(v, 0) + 1
print("Round", rnd, tally)Round 1 {'yes': 2, 'no': 1}
Round 2 {'no': 1}Common mistakes
Storing the result of clear()
clear() returns None. d = d.clear() leaves you with None instead of an empty dictionary.
d = {"x": 1}
d = d.clear()
print(d)None
Questions people ask
How do I empty a dictionary in Python?
d.clear() empties it in place. d = {} gives the name a new empty dictionary instead.
How do I remove just one key?
Use dict.pop() or del d[key].
Is clear() the same for lists and sets?
Yes, list.clear() and set.clear() work the same way.