W3docs

Python Dictionary Methods

Master all Python dictionary methods with clear explanations, runnable examples, and common gotchas for keys, values, items, get, update, pop, and more.

Python dictionaries store data as key-value pairs and ship with a rich set of built-in methods for reading, adding, updating, and removing entries. This chapter covers every dictionary method available in Python 3, with correct examples and practical notes on when — and when not — to use each one.

For a general introduction to dictionaries (creation, accessing items, nesting), see the Python Dictionaries chapter.

What is a Python Dictionary?

A dictionary maps unique keys to values. Keys must be hashable (strings, numbers, and tuples of hashables all work; lists do not). Values can be any Python object.

person = {"name": "Alice", "age": 28, "city": "Berlin"}

Dictionaries maintain insertion order since Python 3.7 — iterating them always yields keys in the order they were added.

Dictionary Methods at a Glance

MethodReturnsPurpose
clear()NoneRemove all items
copy()dictShallow copy
fromkeys(keys, value)dictNew dict from key sequence
get(key, default)value or defaultSafe key lookup
items()viewKey-value pairs
keys()viewAll keys
values()viewAll values
pop(key, default)valueRemove and return a value
popitem()(key, value)Remove and return last item
setdefault(key, default)valueInsert key if absent
update(other)NoneMerge another dict or iterable

clear()

clear() removes every item from the dictionary in place, leaving an empty dict. Use it when you need to reuse the same dict object rather than creating a new one.

python— editable, runs on the server

Gotcha: inventory = {} looks similar but creates a new dict object. If another variable points to the same dict, clear() empties it for both; reassignment does not.

a = {"x": 1}
b = a
a.clear()
print(b)   # Output: {}  — b sees the change

a = {"x": 1}
b = a
a = {}
print(b)   # Output: {'x': 1}  — b is unaffected

copy()

copy() returns a shallow copy — a new dict with the same keys and references to the same values.

python— editable, runs on the server

Gotcha: If any value is a mutable object (list, dict, set), both the original and the copy share that object. Use copy.deepcopy() when you need full independence.

For more details on copying dicts safely, see Copy Dictionaries.


fromkeys()

fromkeys(iterable, value) is a class method that builds a new dict from a sequence of keys, all mapped to the same value (default None).

fields = ["name", "email", "phone"]
record = dict.fromkeys(fields, "")
print(record)
# Output: {'name': '', 'email': '', 'phone': ''}

Gotcha: If the default value is mutable (e.g., a list), all keys share the same object:

bad = dict.fromkeys(["a", "b"], [])
bad["a"].append(1)
print(bad)  # Output: {'a': [1], 'b': [1]}  — both share the list!

The fix is to use a dict comprehension instead:

good = {k: [] for k in ["a", "b"]}
good["a"].append(1)
print(good)  # Output: {'a': [1], 'b': []}

get()

get(key, default=None) returns the value for key if it exists, or default otherwise. It never raises KeyError.

python— editable, runs on the server

When to use it: prefer get() over dict[key] whenever the key may be absent. Use the two-argument form to supply a meaningful default rather than catching KeyError in a try/except.


items()

items() returns a dict_items view — an iterable of (key, value) tuples that reflects the current state of the dict.

python— editable, runs on the server

The most common use is unpacking key and value in a for loop:

scores = {"math": 90, "english": 85, "science": 92}
for subject, grade in scores.items():
    print(f"{subject}: {grade}")
# Output:
# math: 90
# english: 85
# science: 92

Views are live — they reflect changes to the dict without needing to be regenerated.

For more loop patterns, see Loop Dictionaries.


keys()

keys() returns a dict_keys view of all keys in insertion order.

python— editable, runs on the server

Because it is a view, you can use it in set operations to compare two dicts:

a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}

print(a.keys() & b.keys())  # Output: {'y'}    — keys in both
print(a.keys() | b.keys())  # Output: {'x', 'y', 'z'}  — all keys
print(a.keys() - b.keys())  # Output: {'x'}    — keys only in a

values()

values() returns a dict_values view of all values.

python— editable, runs on the server

Common use cases:

prices = {"apple": 0.99, "banana": 0.59, "cherry": 2.49}

total = sum(prices.values())
print(f"Total: {total:.2f}")   # Output: Total: 4.07

most_expensive = max(prices.values())
print(most_expensive)          # Output: 2.49

Unlike keys(), values() does not support set operations because values are not guaranteed to be unique.


pop()

pop(key, default) removes the item with the given key and returns its value. If the key is missing and no default is given, it raises KeyError.

python— editable, runs on the server

When to use it: pop() is the right tool when you need to both remove an item and use its value in the same operation, such as processing items from a queue-like dict.


popitem()

popitem() removes and returns the last inserted key-value pair as a (key, value) tuple. Calling it on an empty dict raises KeyError.

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

last = data.popitem()
print(last)   # Output: ('c', 3)
print(data)   # Output: {'a': 1, 'b': 2}

A practical pattern is processing a dict destructively until it is empty:

tasks = {"write tests": True, "review PR": False, "deploy": True}
while tasks:
    name, done = tasks.popitem()
    status = "done" if done else "pending"
    print(f"{name}: {status}")

setdefault()

setdefault(key, default=None) returns the value for key if it exists. If key is absent, it inserts it with default and returns default.

options = {"color": "blue"}

# Key exists — returns existing value, does NOT overwrite
print(options.setdefault("color", "red"))   # Output: blue

# Key absent — inserts and returns default
print(options.setdefault("size", "medium")) # Output: medium

print(options)
# Output: {'color': 'blue', 'size': 'medium'}

Primary use case: building dictionaries of lists (grouping):

words = ["apple", "avocado", "banana", "blueberry", "cherry"]
grouped = {}
for word in words:
    grouped.setdefault(word[0], []).append(word)

print(grouped)
# Output: {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}

This is cleaner than an if key not in d: d[key] = [] check on each iteration.


update()

update(other) merges other into the dictionary, overwriting existing keys. other can be another dict, an iterable of (key, value) pairs, or keyword arguments.

python— editable, runs on the server

Python 3.9+ alternative: the |= merge-in-place operator does the same thing in a more concise way:

profile = {"name": "Alice", "age": 28}
profile |= {"age": 29, "city": "Berlin"}
print(profile)
# Output: {'name': 'Alice', 'age': 29, 'city': 'Berlin'}

The | operator (without =) returns a new dict instead of modifying in place.


Accessing and Modifying Items

Beyond the methods above, Python provides direct syntax for reading, adding, and removing dictionary entries.

Read a value by key:

python— editable, runs on the server

Accessing a key that does not exist raises KeyError. Use get() to avoid this.

Add or overwrite a value:

person = {"name": "Alice", "age": 28}
person["occupation"] = "Engineer"  # new key
person["age"] = 29                 # overwrite existing key
print(person)
# Output: {'name': 'Alice', 'age': 29, 'occupation': 'Engineer'}

Loop through keys and values:

python— editable, runs on the server

Choosing the Right Method

GoalBest approach
Read a value, crash if missingd[key]
Read a value safelyd.get(key, default)
Remove and use a valued.pop(key)
Insert only if absentd.setdefault(key, default)
Merge another dictd.update(other) or d |= other (3.9+)
Iterate key-value pairsfor k, v in d.items()
Check for a keykey in d
Empty a shared dict objectd.clear()
Create from a key listdict.fromkeys(keys, value)

Practice

Practice
What are some of the methods available in Python for working with dictionary?
What are some of the methods available in Python for working with dictionary?
Was this page helpful?