Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

How to Add Items to a Python Dictionary: Methods and Tradeoffs

Learn how to add items to Python dictionaries using assignment, update(), setdefault(), and the | operator, and when each approach is the best fit.

~5 min readPython
#dictionary#python syntax#data structures#update method
Illustration of adding a key-value pair to a Python dictionary with a plus symbol.

When you need to add an item to a Python dictionary, the most direct approach is assignment: d[key] = value. This works for new keys and overwrites existing ones. Depending on whether you are adding one item, many items, or merging from another dictionary, other methods like update(), setdefault(), and the | operator may be more appropriate. This article covers the practical ways to add items to a dictionary, how each method behaves, and the tradeoffs that matter in real code.

Basic Assignment and Key Collision Behavior

The simplest way to add a key-value pair is direct assignment:

python
config = {} config["host"] = "localhost" config["port"] = 8080

If the key already exists, assignment replaces the old value. That is usually what you want when updating a configuration value. But if you need to preserve the original value and only add when the key is absent, assignment is the wrong tool because it silently overwrites.

python
settings = {"theme": "dark"} settings["theme"] = "light" # overwrites

For conditional insertion, use a method that checks existence first, such as setdefault() or an explicit if key not in d test.

Using update() to Add Multiple Items

When you have several key-value pairs to add at once, update() accepts a dictionary, an iterable of key-value tuples, or keyword arguments.

python
server = {"host": "example.com"} server.update({"port": 443, "tls": True}) # or server.update([("port", 443), ("tls", True)]) # or server.update(port=443, tls=True)

update() also overwrites existing keys. It is a single call, which is more readable than multiple assignments when you are adding several keys. It modifies the dictionary in place and returns None.

One subtle point: literal keyword arguments must be valid Python identifiers, so a key like "server-port" cannot be written as server.update(server-port=443). You can still store that key by passing a dictionary or an iterable of key-value tuples, or by unpacking a dictionary with **: server.update(**{"server-port": 443}).

setdefault() for Conditional Insertion

setdefault(key, default) returns the current value if the key exists; otherwise it inserts the key with the default value and returns that default. This is useful for building counters or accumulating data without an explicit if check.

python
occurrences = {} for word in ["apple", "banana", "apple"]: occurrences.setdefault(word, 0) occurrences[word] += 1

A more concise pattern uses setdefault to initialize a list before appending:

python
groups = {} for item in [("a", 1), ("b", 2), ("a", 3)]: groups.setdefault(item[0], []).append(item[1])

Concurrency note: setdefault handles a single read-or-insert operation, but it does not make a longer read-modify-write sequence atomic. If multiple threads update the same dictionary, use a lock or a concurrency-friendly data structure.

Also, the default argument is evaluated eagerly, even if the key exists. So setdefault(key, expensive_function()) always calls expensive_function(), which may be a performance concern.

Merging Dictionaries with | and Dict Unpacking

Python 3.9 introduced the union operator | for dictionaries, which returns a new dictionary that combines two existing ones. The right-hand dictionary takes precedence for overlapping keys.

python
defaults = {"timeout": 30, "retries": 3} user = {"timeout": 60} merged = defaults | user # {'timeout': 60, 'retries': 3}

There is also the augmented assignment |= which updates the left-hand dictionary in place:

python
defaults |= user

Before 3.9, the common idiom was {**a, **b}. Both | and {**a, **b} create a new dictionary, while |= mutates the left operand. If you need to preserve the original dictionaries, | is cleaner. If you are merging in a loop, |= avoids repeated copying.

Adding Items in Loops and Comprehensions

When building a dictionary from a sequence, a comprehension is often more readable than a loop with assignment.

python
squares = {x: x**2 for x in range(10)}

For more complex logic, a loop with direct assignment is fine. Avoid calling update() in every iteration unless you have a batch of pairs to add at once.

python
result = {} for key, value in raw_data: result[key] = transform(value)

A common mistake is to use dict.fromkeys() with a mutable default value, which shares the same object across all keys:

python
# Wrong: all keys share the same list bad = dict.fromkeys(["a", "b"], []) bad["a"].append(1) # bad["b"] also gets 1

Use a comprehension or setdefault when each key needs a distinct mutable value.

Performance and Memory Considerations

Adding items to a dictionary is amortized O(1) on average, but the practical differences between these methods are usually small. Assignment is the most direct way to add one item. update() is convenient when you have a batch of pairs. If you are choosing between setdefault and an if key not in d check followed by assignment, benchmark with your own data; the fastest choice can depend on the Python implementation and on whether the key is usually present.

Memory usage is more subtle. Each dictionary entry stores a hash, a key reference, and a value reference. When you add many items, the dictionary may need to resize its internal hash table, which temporarily requires extra memory. If you know the final keys in advance, you can pre-populate with dict.fromkeys() or by constructing a dictionary from an existing collection, but this is rarely necessary unless memory is tight.

When you merge dictionaries, keep in mind that the operation copies references, not the objects themselves. Reassigning a key in one dictionary after a merge does not change the merged dictionary; mutating a mutable value shared by both dictionaries would be visible in both.

Choosing the Right Method for Your Use Case

The decision among these methods comes down to what you need:

MethodUse caseBehavior on existing key
d[key] = valueSingle item, overwrite allowedOverwrites
d.update(...)Multiple items, overwrite allowedOverwrites
d.setdefault(key, default)Add only if missingKeeps existing value
`d1d2`Merge into new dict, right wins
`d1= d2`Merge into existing dict

If you are adding a single item and want to avoid overwriting an existing value, use setdefault or an explicit if key not in d check. The explicit check is more readable when the default value is expensive to compute:

python
if key not in d: d[key] = expensive_default()

If you are merging two dictionaries and need to preserve the original, use |. If you are building a dictionary incrementally in a loop and the number of items is dynamic, direct assignment is clear and efficient. If you find yourself writing repeated if checks for the same key, consider setdefault or a defaultdict from the collections module, which provides a more elegant way to handle missing keys.

Compatibility note: | and |= require Python 3.9 or later. For Python 3.5 through 3.8, {**a, **b} is the clearest merging approach. dict(a, **b) also merges, but the **b keyword arguments must be strings. For code that must support versions older than 3.5, build a new dictionary and call .update() instead.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.