python
dictionary
extend
programming
data-structures

Python extend for a dictionary

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Python dictionaries do not have an extend method because they are key-value mappings, not sequence containers like lists. The equivalent operation is usually merging one mapping into another, either mutating in place (update) or creating a new merged dictionary. Choosing the right merge strategy depends on overwrite behavior, nested structures, and whether you need immutable-style code. This article explains practical dictionary merge patterns, including modern syntax, controlled conflict handling, and deep-merge approaches for nested configs.

Basic In-Place Merge with update

update is the classic mutable operation.

python
1base = {"host": "localhost", "port": 5432}
2override = {"port": 5433, "ssl": True}
3
4base.update(override)
5print(base)
6# {'host': 'localhost', 'port': 5433, 'ssl': True}

Existing keys are overwritten by incoming values. This is efficient and explicit when mutation is acceptable.

Create a New Merged Dictionary

If you prefer not to mutate the original dictionary, use unpacking or union operators.

python
1base = {"a": 1, "b": 2}
2extra = {"b": 99, "c": 3}
3
4merged = {**base, **extra}
5# Python 3.9+
6merged2 = base | extra
7
8print(merged)
9print(merged2)

In both cases, right-side values win on key conflicts.

Merge with Conflict Rules

Sometimes overwrite-on-conflict is wrong. You may want to keep existing values, sum numeric values, or combine lists.

python
1def merge_keep_existing(dst, src):
2    out = dict(dst)
3    for k, v in src.items():
4        out.setdefault(k, v)
5    return out
6
7print(merge_keep_existing({"a": 1}, {"a": 2, "b": 3}))
8# {'a': 1, 'b': 3}

Custom merge logic makes intent explicit and avoids hidden behavior.

Deep Merge for Nested Dictionaries

update and | are shallow: nested dicts are replaced, not merged recursively.

python
1left = {"db": {"host": "localhost", "port": 5432}}
2right = {"db": {"port": 5433}}
3
4print(left | right)
5# {'db': {'port': 5433}}

If you need nested merge behavior:

python
1def deep_merge(a, b):
2    out = dict(a)
3    for k, v in b.items():
4        if k in out and isinstance(out[k], dict) and isinstance(v, dict):
5            out[k] = deep_merge(out[k], v)
6        else:
7            out[k] = v
8    return out
9
10print(deep_merge(left, right))
11# {'db': {'host': 'localhost', 'port': 5433}}

Choose shallow vs deep behavior intentionally, especially in configuration systems.

Practical Verification Workflow

A reliable way to avoid regressions is to validate the solution in three passes: baseline, controlled change, and repeatability check. First, capture a baseline outcome before you apply fixes. This could be a failing command, a wrong output sample, a stack trace, or a screenshot of current behavior. Second, apply one focused change and rerun exactly the same checks so you can attribute improvements to a specific edit. Third, rerun the checks multiple times or with slightly different inputs to ensure the fix is not accidental or data-specific.

A lightweight template you can adapt for most projects looks like this:

bash
1# 1) reproduce current behavior
2./run_example.sh > before.txt
3
4# 2) apply your change
5# edit config/code based on this article
6
7# 3) verify behavior after change
8./run_example.sh > after.txt
9diff -u before.txt after.txt

If your environment involves tests, add at least one focused regression test that would fail before the fix and pass after it. This turns a one-time troubleshooting success into a durable maintenance improvement, which is especially important when teams rotate ownership or upgrade dependencies later.

Common Pitfalls

  • Looking for a non-existent dict.extend() API instead of using merge operations.
  • Forgetting that update mutates the original dictionary in place.
  • Assuming | or update performs deep merges on nested mappings.
  • Relying on implicit conflict behavior instead of defining merge policy explicitly.
  • Mixing incompatible value types on the same key without validation.

Summary

For dictionaries, update (mutable), unpacking/union (immutable-style), and custom merge functions are the right alternatives to a hypothetical extend. Pick the method based on mutation needs and conflict semantics. If data is nested, implement or use a deep-merge strategy explicitly so results match intent.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.