dict.clear()

dict.clear()
Returns: None · Updated March 13, 2026 · Dict Methods
dictionaries methods mutation

The .clear() method removes all key-value pairs from a dictionary, leaving it empty. It modifies the dictionary in-place and returns None.

Syntax

dict.clear()

Parameters

None. This method takes no parameters.

Examples

Basic usage

Remove all items from a dictionary:

scores = {"alice": 95, "bob": 87, "charlie": 92}
scores.clear()
print(scores)
# {}

Clearing a temporary dictionary

A common pattern involves clearing a dictionary used as a cache or accumulator:

counts = {}
for word in ["apple", "banana", "apple", "cherry", "banana", "apple"]:
    counts[word] = counts.get(word, 0) + 1

print(counts)
# {apple: 3, banana: 2, cherry: 1}

# Process the counts...
total = sum(counts.values())

# Reset for next use
counts.clear()

Avoiding the mutable default argument pitfall

A subtle issue: if you store a reference to a dictionary and then clear it, you affect all references:

original = {"key": "value"}
backup = original

original.clear()
print(backup)
# {}  # Both are now empty!

# To preserve a snapshot, make a copy first:
original = {"key": "value"}
snapshot = original.copy()
original.clear()
print(original)   # {}
print(snapshot)  # {key: value}

Common Patterns

Resetting a running total

total_sales = {}

# Add some sales
total_sales["january"] = 5000
total_sales["february"] = 7500

# Process and then reset for next quarter
print(f"Q1 total: {sum(total_sales.values())}")
total_sales.clear()

Clearing after iteration

Sometimes you need to clear a dictionary mid-iteration:

cache = {"a": 1, "b": 2, "c": 3}

# Process items up to a threshold
threshold = 2
to_process = {k: v for k, v in cache.items() if v <= threshold}
cache.clear()
cache.update(to_process)

print(cache)
# {a: 1, b: 2}

See Also

  • modules::collections — contains defaultdict and Counter which work with dictionaries

  • dict() — the dict constructor for creating new dictionaries