Add a new item to a dictionary in Python
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Adding items to a Python dictionary is done with bracket assignment (d[key] = value), the update() method, the merge operator (|=, Python 3.9+), or setdefault() for conditional insertion. Dictionaries are mutable hash maps with O(1) average-case insertion and lookup. Keys must be hashable (strings, numbers, tuples of immutables), while values can be any object. This article covers all insertion methods with practical examples.
Bracket Assignment (Most Common)
Bracket assignment adds the key if it doesn't exist, or overwrites the value if it does. This is the most common and most readable approach.
The update() Method
update() accepts a dictionary, keyword arguments, or an iterable of key-value pairs. Existing keys are overwritten by the new values.
Merge Operator (Python 3.9+)
The | operator creates a new dictionary. The |= operator updates the left dictionary in place. Both give priority to the right-hand operand for duplicate keys.
setdefault() for Conditional Insertion
setdefault(key, default) returns the existing value if the key exists, or inserts default and returns it if the key is missing. It's ideal for building lists or nested structures without checking key existence first.
Dictionary Comprehension
Nested Dictionary Insertion
Common Pitfalls
- Accidental key overwrite: Bracket assignment silently overwrites existing keys. Use
setdefault()or checkif key not in dwhen you want to preserve existing values. - Unhashable keys: Lists, sets, and dictionaries cannot be dictionary keys because they are mutable. Use tuples instead of lists if you need a composite key.
- Mutating during iteration: Adding or removing keys while iterating over a dictionary raises
RuntimeError. Create a copy first (for k in list(d.keys())) or collect changes and apply them after the loop. - Confusing
update()overwrite behavior:update()silently overwrites existing keys with new values. If you need to merge without overwriting, usesetdefault()or conditional logic. - Forgetting
|=requires Python 3.9+: The merge operator (|and|=) is only available in Python 3.9 and later. Useupdate()or{**d1, **d2}for older versions.
Summary
d[key] = value— add or overwrite a single key (most common)d.update(other)— add multiple keys from a dict, keyword args, or iterable of pairsd |= other— merge operator for in-place update (Python 3.9+)d.setdefault(key, default)— insert only if key is missing- Dictionary comprehension — create or transform dictionaries from iterables
- Keys must be hashable; values can be any type

