Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Merge two dictionaries with later values overwriting earlier ones

Create a new dictionary by merging two dictionaries where keys in the second dictionary overwrite those in the first.

Python practice14 minModules & Standard LibraryIntermediateLast updated March 23, 2026

Problem statement

Given two dictionaries d1 and d2, return a new dictionary containing all keys from both dictionaries. If a key appears in both dictionaries, the value from d2 should overwrite the value from d1. The original dictionaries must not be modified.

Task

Write a function merge_dicts(d1, d2) that returns a new dictionary containing all keys from both inputs; if a key exists in both, the value from d2 should be used.

Examples

Basic overwrite

Input

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

Output

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

The key 'b' exists in both; the value from the second dictionary (3) overwrites the first (2). The merged dictionary preserves insertion order: keys from d1 first (in their order), then new keys from d2.

Input format

Two dictionaries provided as function arguments: merge_dicts(d1, d2)

Output format

A single dictionary containing merged key-value pairs

Constraints

- Do not mutate the input dictionaries. - Keys may be any hashable type. - Keep deterministic insertion order by constructing the result from d1 then d2.

Samples

Sample 1

Input

merge_dicts({'x': 10}, {'y': 20})

Output

{'x': 10, 'y': 20}

No overlapping keys; result contains both in that order.