Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Problem No 4

Merge two dictionaries

Easy

6 minute session

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'.

Code editor
Loading editor…

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.

07:43 PM

Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.