Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Merge two dictionaries

Combine two dictionaries into one, with the second dictionary's values overwriting duplicate keys from the first.

Python practice6 minDictionaries & SetsBeginnerLast updated March 18, 2026

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}

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 1

Input

merge_dicts({'a': 1, 'b': 2}, {'b': 3, 'c': 4})

Output

{'a': 1, 'b': 3, 'c': 4}

Key 'b' is present in both; the value from the second dictionary (3) overwrites the first. Key order is 'a', 'b', 'c'.