Python Add to Dictionary: Add Key-Value Pairs, Update, and Append

Learn how to add to a dictionary in Python using key assignment, update(), setdefault(), |=, and dictionary unpacking, with examples for single keys, multiple keys, lists, nested dictionaries, and existing keys.

Published

Updated

Read time 5 min read

Reviewed byDeepak Prasad

Python Add to Dictionary: Add Key-Value Pairs, Update, and Append

Dictionaries map keys to values. “Adding” usually means inserting a new key, merging in another mapping, or updating a mutable value (like a list) stored under an existing key. This guide covers assignment, update, setdefault, merge operators, unpacking, nested paths, duplicate-key behavior, and a few mistakes to avoid.

For background on how dicts work, see Python dictionary. For deeper nesting patterns, see nested dictionary in Python; for merging whole dicts as snapshots, see merge dictionaries in Python. To sort results, see sort dictionary by key.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


Add a key-value pair to a dictionary

Use subscript assignment. If the key is new, Python adds the pair; if the key already exists, the value is replaced (dicts never store two identical keys).

python
scores = {}
scores['ada'] = 100
scores['lin'] = 98
print(scores)
Output

That prints two entries. The same syntax updates scores['ada'] if you assign again.


Add multiple key-value pairs using update()

dict.update() accepts another mapping or an iterable of (key, value) pairs and merges them into the left-hand dict in place. When keys overlap, values from the argument win.

python
user = {'name': 'Ada', 'role': 'dev'}
user.update({'role': 'lead', 'team': 'platform'})
print(user)
Output

role becomes lead and team is added. You can also pass keyword arguments: user.update(team='platform') when keys are valid identifiers.


Add a key only if it does not exist

setdefault(key, default) returns the current value for key if present; otherwise it stores default under key and returns that default. It is a single call for “insert if missing.”

python
cfg = {'debug': True}
cfg.setdefault('port', 8080)
cfg.setdefault('debug', False)
print(cfg)
Output

port is added as 8080; debug stays True because the key already existed. For clearer branching, if 'port' not in cfg: cfg['port'] = 8080 is equivalent when you do not need the return value.


Add values to a dictionary key

Sometimes the key already exists and the value is a mutable container (list, set, another dict) or a number you want to accumulate.

Add item to a list inside a dictionary

python
buckets = {'tags': ['alpha']}
buckets['tags'].append('beta')
print(buckets)
Output

If tags might be missing, create the list first with setdefault or an if guard:

python
buckets = {}
buckets.setdefault('tags', []).append('gamma')
print(buckets)
Output

Add count or increment existing value

python
counts = {}
for word in ['run', 'run', 'walk']:
    counts[word] = counts.get(word, 0) + 1
print(counts)
Output

get(word, 0) supplies zero when the key is absent, then you store the incremented total.


Add dictionary to another dictionary

Update the original dictionary

Use update or the augmented merge operator |= (Python 3.9+). Both mutate the left dict; on duplicate keys, the right-hand side wins.

python
base = {'a': 1}
extra = {'b': 2, 'a': 99}
base |= extra
print(base)
Output

a becomes 99 and b is added.

Create a new dictionary without changing the original

Use dictionary unpacking or the merge operator | (3.9+) so the originals stay untouched.

python
left = {'a': 1, 'b': 2}
right = {'b': 3, 'c': 4}
merged = left | right
print('left:', left)
print('merged:', merged)
Output

left is unchanged; merged has b from right. The older spelling merged = {**left, **right} works from Python 3.5 onward with the same duplicate-key rule.


Add to nested dictionary in Python

Assign through each level of keys. If an inner dict might be missing, insert it first.

python
data = {}
data.setdefault('user', {})
data['user']['name'] = 'Ada'
print(data)
Output

For larger trees, keep inner dicts as defaultdict or build helpers—patterns in nested dictionary in Python apply here.


What happens if the key already exists?

Dict keys are unique. Assigning d[k] = v, merging with update / |=, or using {**a, **b} / a | b replaces the value for k instead of creating a second entry. If you need to preserve old values, store them under a new key or use a list as the value.

python
d = {'score': 10}
d['score'] = 99
print(d)

left = {'id': 1, 'label': 'first'}
right = {'id': 2, 'note': 'patch'}
print('merge |:', left | right)
Output

After the first block, d is only {'score': 99}—there is never a second score key. The merge shows the same rule for overlaps: id comes from right while label stays from left because only right supplies id and note; shared key id ends as 2, not 1.


update() vs setdefault() vs |=

Tool Typical use Mutates original?
d[key] = value One explicit key Yes
d.update(m) Many keys from a mapping or pairs Yes
d.setdefault(k, default) Insert only when k missing; returns stored value Yes (if key added)
d |= m (3.9+) Merge mapping into d like update Yes
d | m (3.9+) New merged dict No

setdefault is for “ensure key exists with this default”; update and |= are for bulk merges; | is for a fresh dict without touching inputs.


Common mistakes when adding to a dictionary

  • Assuming duplicate keys are allowed: only the last assignment for a given key survives.
  • Doing d['items'].append(x) when 'items' was never created—use setdefault('items', []) or check membership first.
  • Merging with {**a, **b} expecting a deep merge of nested dicts; top-level keys are shallow-merged (inner dicts are replaced wholesale). See the merge guide linked above.
  • Building giant intermediate lists with dict(list(a.items()) + list(b.items())): it is harder to read than update or | and allocates extra structures.

Python add to dictionary quick reference table

Goal Pattern
One new or updated key d[key] = value
Many keys, in place d.update(other) or d |= other (3.9+)
New dict, leave inputs alone d | other or {**d, **other}
Key if missing d.setdefault(k, default)
Append to list value d.setdefault('k', []).append(x)
Increment counter d[k] = d.get(k, 0) + 1
Nested field d.setdefault('outer', {})['inner'] = v

Summary

Adding to a Python dictionary means either introducing a new key with [] assignment, merging many keys with update or |=, or inserting missing keys with setdefault. Mutable values let you append or increment in place under an existing key. For non-destructive merges, use | or {**a, **b}; remember duplicate keys always overwrite rather than duplicate. Nested structures need each level present before subscripting; shallow merges do not recurse into inner dicts automatically.


References


Frequently Asked Questions

1. How do I add a new key to a dictionary in Python?

Assign with square brackets: d[key] = value; if key is new, the pair is added—if it already exists, the value is replaced.

2. How do I add several keys at once?

Call d.update(other) with another mapping or iterable of pairs, or build a new dict with unpacking like {**d, **other} or with d | other on Python 3.9+.

3. How do I add a key only if it is missing?

Use d.setdefault(key, default) which inserts key with default when absent, or check if key not in d before assignment.

4. What is the difference between update() and |= on a dict?

dict.update() mutates the left dict in place and returns None; d |= other (3.9+) also merges into d in place with the same right-hand-wins rule on duplicate keys; d | other builds a new dict instead.

5. Does appending to a dictionary create duplicate keys?

No—dict keys are unique; assigning to an existing key overwrites the value, so use lists or counters as values when you need to accumulate multiple items under one key.
Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …