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 |
|---|---|
| A view of all keys, in insertion order. |
| A view of all values, in insertion order. |
| A view of |
| The value for |
| Removes |
| Removes and returns the last inserted |
| Merges |
| Returns the value for |
| Removes all entries, leaving an empty dict. |
| 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.
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
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).update(), .clear(), and .copy()
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.
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 |
|---|---|---|---|
| No — mutates | 2.x / 3.x (all versions) | The classic, most widely portable approach. |
| Yes | 3.9+ | Reads left to right; keys in |
| No — mutates | 3.9+ | Shorthand equivalent to |
| Yes | 3.5+ | Most flexible — can merge 3+ dicts and add extra keys inline. |