PythonDictionary Methods

Dictionary Methods

Dictionaries come with a compact set of built-in methods covering the things you do with them constantly: iterating, looking things up safely, removing entries, and merging one dict into another. This page walks through the most useful ones and shows the modern (Python 3.9+) ways to combine dictionaries.

The Core Methods

Method

Returns / Effect

.keys()

A view of all keys, in insertion order.

.values()

A view of all values, in insertion order.

.items()

A view of (key, value) tuples, in insertion order.

.get(key, default)

The value for key, or default (default None) if missing — never raises KeyError.

.pop(key, default)

Removes key and returns its value; returns default (or raises KeyError) if missing.

.popitem()

Removes and returns the last inserted (key, value) pair as a tuple.

.update(other)

Merges other (a dict or iterable of pairs) into this dict in place, overwriting existing keys.

.setdefault(key, default)

Returns the value for key if present; otherwise inserts key with default and returns it.

.clear()

Removes all entries, leaving an empty dict.

.copy()

Returns a shallow copy of the dict.

Iterating with .items()

The most common iteration pattern unpacks each (key, value) pair directly in the for loop header.

Python
prices = {"apple": 0.5, "banana": 0.25, "cherry": 3.0}

for name, price in prices.items():
    print(f"{name}: ${price:.2f}")

# apple: $0.50
# banana: $0.25
# cherry: $3.00

# .keys() and .values() work the same way when you only need one side
for name in prices.keys():
    print(name)          # apple, banana, cherry

for price in prices.values():
    print(price)         # 0.5, 0.25, 3.0
.get(), .pop(), and .setdefault() in Practice

Python
stock = {"apples": 10, "bananas": 5}

print(stock.get("apples"))            # 10
print(stock.get("mangoes", 0))        # 0 -- default when missing

removed = stock.pop("bananas")        # removes "bananas", returns 5
print(removed, stock)                 # 5 {'apples': 10}

# pop with a default avoids KeyError on a missing key
print(stock.pop("mangoes", "n/a"))    # n/a

# setdefault: get-or-insert in one call
stock.setdefault("cherries", 20)      # "cherries" missing -> inserted with 20
stock.setdefault("apples", 999)       # "apples" exists -> unchanged, returns 10
print(stock)   # {'apples': 10, 'cherries': 20}

last = stock.popitem()                # removes the most recently inserted pair
print(last)     # ('cherries', 20)
Note
`.pop(key)` without a default raises `KeyError` if the key is missing, just like `[]` access does. Supplying a default (as in `stock.pop("mangoes", "n/a")` above) makes it safe to call on keys you are not sure exist.
.update(), .clear(), and .copy()

Python
base = {"a": 1, "b": 2}

base.update({"b": 20, "c": 3})   # overwrites "b", adds "c"
print(base)   # {'a': 1, 'b': 20, 'c': 3}

snapshot = base.copy()           # shallow copy, independent top-level dict
snapshot["a"] = 999
print(base)       # {'a': 1, 'b': 20, 'c': 3}      -- unchanged
print(snapshot)   # {'a': 999, 'b': 20, 'c': 3}

base.clear()
print(base)   # {}
Merging Dictionaries: `|` and `**`

Python 3.9 introduced the | (union) and |= operators for merging dicts, giving a clean expression-based alternative to calling .update(). Dict unpacking with ** inside a new literal is an older technique (works since Python 3.5) that achieves a similar result and also lets you merge more than two dicts at once inline.

Python
defaults = {"theme": "light", "font_size": 12}
overrides = {"font_size": 16, "language": "en"}

# Python 3.9+ merge operator - creates a NEW dict, right side wins on conflicts
merged = defaults | overrides
print(merged)   # {'theme': 'light', 'font_size': 16, 'language': 'en'}

# In-place merge operator - updates defaults directly, like .update()
defaults |= overrides
print(defaults) # {'theme': 'light', 'font_size': 16, 'language': 'en'}

# ** unpacking inside a literal - works since Python 3.5, same "last wins" rule
settings = {**defaults, **overrides, "font_size": 20}
print(settings) # {'theme': 'light', 'font_size': 20, 'language': 'en'}

Technique

Creates new dict?

Minimum Python

Notes

a.update(b)

No — mutates a

2.x / 3.x (all versions)

The classic, most widely portable approach.

a | b

Yes

3.9+

Reads left to right; keys in b win on conflicts.

a |= b

No — mutates a

3.9+

Shorthand equivalent to a.update(b).

{**a, **b}

Yes

3.5+

Most flexible — can merge 3+ dicts and add extra keys inline.

Tip
Prefer `|` for a quick two-dict merge on modern Python, and `{**a, **b, "extra": 1}` when you need to merge several dicts or add ad-hoc keys in a single expression. Reach for `.update()` when you specifically want to mutate an existing dict in place rather than create a new one.