dict.pop()

dict.pop(key[, default])
Returns: any · Updated March 13, 2026 · Dict Methods
dictionaries methods mutation removal

The .pop() method removes the specified key from the dictionary and returns its associated value. If the key is not found and a default value is provided, it returns the default. If no default is provided and the key is missing, a KeyError is raised. This makes .pop() useful for both removing items and retrieving their values in a single operation.

Syntax

dict.pop(key[, default])

Parameters

ParameterTypeDefaultDescription
keyanyRequiredThe key to remove from the dictionary
defaultanyOptionalThe value to return if the key is not found. If omitted and key is missing, raises KeyError

Return Value

Returns the value associated with key if it exists. If the key is not found:

  • With default: returns default
  • Without default: raises KeyError

Examples

Basic usage - removing a key-value pair

Remove a key and get its value:

person = {"name": "Alice", "age": 30, "city": "New York"}

age = person.pop("age")
print(age)
# 30

print(person)
# {'name': 'Alice', 'city': 'New York'}

Using with a default value

Provide a default to avoid KeyError:

config = {"host": "localhost", "port": 8080}

timeout = config.pop("timeout", 30)
print(timeout)
# 30

print(config)
# {'host': 'localhost', 'port': 8080}

Without default - KeyError example

When no default is provided and key is missing:

data = {"key": "value"}

# Safe pattern: always provide a default
result = data.pop("missing", None)
print(result)
# None

Practical pattern - consuming dictionary items

A common use case is processing and removing items:

queue = {"task1": "pending", "task2": "pending", "task3": "pending"}

while queue:
    task = queue.popitem()
    print(f"Processing: {task}")
# Processing: ('task3', 'pending')
# Processing: ('task2', 'pending')
# Processing: ('task1', 'pending')

Using pop in a loop

Be careful when modifying a dictionary during iteration:

scores = {"alice": 95, "bob": 87, "charlie": 92, "diana": 88}

while scores:
    name, score = scores.popitem()
    if score >= 90:
        print(f"{name} passed with {score}")

print(scores)
# {}

Extracting and transforming

Sometimes you want to extract a value and transform it in one step:

user = {"name": "alice", "role": "admin"}

name = user.pop("name")
print(name.upper())
# ALICE

role = user.pop("role", "guest")
print(f"Role: {role}")
# Role: admin

Conditional removal

Only remove if a condition is met:

cache = {"data": "expensive", "temp": "quick", "metadata": "info"}

if cache.get("temp") == "quick":
    cache.pop("temp")

print(cache)
# {'data': 'expensive', 'metadata': 'info'}

Common Patterns

Cache eviction

Simulating cache with manual eviction:

cache = {"page1": "content1", "page2": "content2"}

def get_page(key):
    if key in cache:
        return cache.pop(key)
    return fetch_from_disk(key)

def fetch_from_disk(key):
    return f"loaded {key}"

State machine transitions

Managing state transitions in a workflow:

states = {"step1": "completed", "step2": "current", "step3": "pending"}

current = states.pop("step2", None)
if current:
    states["step2"] = "completed"
    states["step3"] = "current"
    print(f"Transitioned from {current}")

Getting items with defaults

A clean way to get and remove in one call:

def process_request(headers, required_header):
    value = headers.pop(required_header, None)
    if value is None:
        raise ValueError(f"Missing required header: {required_header}")
    return value

Performance Note

  • .pop() is an O(1) operation - constant time for removing a known key
  • Dictionary order is preserved in Python 3.7+ - .pop() removes a specific key, not the last added
  • Unlike .popitem(), .pop(key) removes a specific key by value

See Also

  • dict.get() - safely retrieve a value without removing the key
  • dict.copy() - create a shallow copy before mutating a dictionary
  • dict() - the dict constructor for creating new dictionaries