Lesson guide
What this Python exercise practices
Merge two dictionaries is a beginner practice lesson that focuses on functions, parameters, return values. It is designed to be solved in about 6 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- Function parameters
- Return values
Difficulty and time
- Level
- Beginner
- Estimated time
- 6 minutes
Practice path
Summary
Combine two dictionaries into one, with the second dictionary's values overwriting duplicate keys from the first.
Problem statement
Given two dictionaries, create and return a new dictionary that contains all key-value pairs from the first and second dictionary. When a key appears in both dictionaries, the value from the second dictionary should overwrite the value from the first. Do not modify the original input dictionaries.
Task
Write a function that returns a new dictionary containing keys from both input dictionaries. If the same key exists in both, the value from the second dictionary should be used.
Examples
Different keys
Input
merge_dicts({'a': 1}, {'b': 2})
Output
{'a': 1, 'b': 2}
Explanation
Both keys are kept; the resulting dictionary has keys 'a' then 'b'.
Input format
Two Python dictionaries passed as arguments to merge_dicts(d1, d2).
Output format
A single Python dictionary that is the merged result.
Constraints
Both inputs will be dictionaries. Keys are hashable. Preserve insertion order: keys from the first dictionary should appear first (unless overwritten), followed by any new keys from the second dictionary.
Samples
Sample input 0
merge_dicts({'a': 1, 'b': 2}, {'b': 3, 'c': 4})
Sample output 0
{'a': 1, 'b': 3, 'c': 4}
Explanation 0
Key 'b' is present in both; the value from the second dictionary (3) overwrites the first. Key order is 'a', 'b', 'c'.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.