Question
I want to merge two Python dictionaries into a new dictionary using a single expression.
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = merge(x, y)
print(z)
# {'a': 1, 'b': 3, 'c': 4}
If the same key exists in both dictionaries, the value from y should overwrite the value from x. What is the correct Pythonic way to do this?
Short Answer
By the end of this page, you will understand how dictionary merging works in Python, how key conflicts are resolved, and how to combine dictionaries into a new one using modern and older Python syntax. You will also see common mistakes, practical examples, and patterns used in real codebases.
Concept
In Python, a dictionary stores data as key-value pairs. Merging dictionaries means combining the pairs from two or more dictionaries into one new dictionary.
The key rule in your question is:
- keep all keys from both dictionaries
- if the same key appears in both, the value from the later dictionary should win
For example:
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
When merged:
{'a': 1, 'b': 3, 'c': 4}
The key 'b' exists in both dictionaries, so the value from y replaces the value from x.
This matters in real programming because dictionaries are often used for:
- configuration settings
- API response data
- user input
- default values overridden by custom values
- combining computed results
Python gives you several ways to merge dictionaries. The best choice depends on your Python version and whether you want to create a new dictionary or .
Mental Model
Think of a dictionary like a labeled set of sticky notes.
xis one board of notesyis another board of notes- merging means copying all notes onto a new board
If both boards have a note with the same label, you cannot keep both under the same label. The later board's note replaces the earlier one.
So when you merge x and then y, you are saying:
- start with everything from
x - place everything from
yon top - if
yuses a label that already exists, its note covers the old one
That is why the value from y wins when keys overlap.
Syntax and Examples
Modern syntax
In Python 3.9 and later, you can use the dictionary merge operator:
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = x | y
print(z)
# {'a': 1, 'b': 3, 'c': 4}
This creates a new dictionary.
Compatible syntax for older Python versions
In Python 3.5 and later, dictionary unpacking is a common solution:
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}
print(z)
# {'a': 1, 'b': 3, 'c': 4}
This also creates a new dictionary, and later unpacked dictionaries override earlier ones.
Updating an existing dictionary
If you want to modify one dictionary in place instead of creating a new one:
x = {'a': 1, 'b': 2}
y = {'b': , : }
x.update(y)
(x)
Step by Step Execution
Consider this example:
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}
Here is what happens step by step:
-
Python starts building a new empty dictionary for
z. -
**xadds all key-value pairs fromx:{'a': 1, 'b': 2} -
**ythen adds all key-value pairs fromy. -
Python sees that
'b'already exists. -
The new value from
yreplaces the old value fromx. -
'c'is new, so it gets added.
Final result:
Real World Use Cases
Dictionary merging is very common in Python programs.
Configuration systems
You may have default settings and user overrides:
default_config = {'debug': False, 'port': 5000}
user_config = {'port': 8000}
config = default_config | user_config
API data processing
You may combine data from different sources:
user = {'id': 1, 'name': 'Ava'}
profile = {'name': 'Ava Smith', 'city': 'London'}
full_data = user | profile
Form or request handling
You might start with defaults, then apply submitted values:
defaults = {'newsletter': False, 'role': 'user'}
submitted = {'newsletter': True}
result = defaults | submitted
Test setup
Tests often begin with a base object and override only one or two values:
base_payload = {: , : }
test_payload = base_payload | {: }
Real Codebase Usage
In real projects, developers use dictionary merging as part of larger patterns.
Defaults plus overrides
A very common pattern is:
settings = defaults | env_values | cli_args
This clearly shows precedence:
- defaults are lowest priority
- environment values override defaults
- command-line arguments override everything
Building new objects without mutating inputs
In production code, creating a new dictionary is often safer than changing an existing one:
new_state = old_state | {'loading': False}
This avoids unexpected side effects.
Guarded merging
Sometimes you only merge if extra values are present:
result = base.copy()
if extra_data:
result |= extra_data
Validation before merge
Developers often validate incoming data before merging it:
def apply_overrides(config, overrides):
allowed = {'host', 'port', 'debug'}
clean = {k: v for k, v in overrides.items() k allowed}
config | clean
Common Mistakes
1. Accidentally mutating the original dictionary
Broken expectation:
x = {'a': 1, 'b': 2}
y = {'b': 3}
x.update(y)
print(x) # x was changed
If you need a new dictionary, use:
z = x | y
or:
z = {**x, **y}
2. Expecting both values for duplicate keys to be kept
A dictionary cannot store the same key twice.
x = {'b': 2}
y = {'b': 3}
z = x | y
print(z)
# {'b': 3}
If you need both values, use a different structure such as a list:
{'b': [2, 3]}
3. Reversing the order
Broken logic:
x = {'b': }
y = {: }
z = y | x
(z)
Comparisons
| Approach | Creates new dictionary? | Modifies existing dictionary? | Python version | Conflict rule |
|---|---|---|---|---|
| `x | y` | Yes | No | 3.9+ |
{**x, **y} | Yes | No | 3.5+ | Later unpack wins |
x.update(y) | No | Yes, x changes | All modern Python versions | y overwrites x |
x.copy(); x.update(y) | Yes | Only the copy changes |
Cheat Sheet
Quick syntax
Python 3.9+
z = x | y
Python 3.5+
z = {**x, **y}
Modify existing dictionary
x.update(y)
Rules
- Dictionaries store unique keys.
- When keys overlap, the later value replaces the earlier one.
x | ymeansyhas higher priority thanx.- Merging dictionaries normally performs a shallow merge.
Examples
{'a': 1} | {'b': 2}
# {'a': 1, 'b': 2}
{'a': 1} | {'a': 9}
# {'a': 9}
{**{'a': 1}, **{: , : }}
FAQ
How do I merge two dictionaries in Python without changing the originals?
Use x | y in Python 3.9+ or {**x, **y} in Python 3.5+. Both create a new dictionary.
Which dictionary wins when keys overlap?
The later dictionary wins. In x | y, the value from y replaces the value from x for duplicate keys.
Is dict.update() the same as merging?
It is similar in result, but it modifies the dictionary in place instead of creating a new one.
Does Python have a built-in merge(x, y) function?
No. Python uses operators and methods like |, unpacking, and update() instead.
Can I merge more than two dictionaries at once?
Yes.
result = a | b | c
or:
result = {**a, **b, **c}
Does dictionary merging work recursively for nested dictionaries?
No, not by default. Standard merging is shallow, so nested dictionaries are replaced, not recursively combined.
Mini Project
Description
Build a small Python utility that combines default application settings with user-provided overrides. This demonstrates practical dictionary merging and shows how later values replace earlier ones.
Goal
Create a function that returns a new configuration dictionary where user settings override default settings.
Requirements
- Create a dictionary of default settings.
- Create a second dictionary containing user overrides.
- Merge them into a new dictionary without changing the original defaults.
- Print the original dictionaries and the merged result.
- Show that overlapping keys use the value from the user overrides.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.