Merge two dictionaries (Python 3.9+ and older) Dry Run in PYTHON

Merge two dictionaries (Python 3.9+ and older) is an interactive PYTHON dry run visualizer from the Dict programs section. Study the source code, then use the execution controls to follow each step, variable update, highlighted line, and console output.

This page provides a browser-based dry run with source-code highlighting, auto-scroll, voice narration controls, and execution output for learning the program step by step.

Merge two dictionaries (Python 3.9+ and older) Program Code

# Merge two dictionaries
dict1 = {"red": 10, "green": 20}
dict2 = {"blue": 30, "yellow": 40}
dict3 = {"green": 25, "purple": 50}  # Overlapping keys

print("Dict1:", dict1)
print("Dict2:", dict2)
print("Dict3 (overlaps):", dict3)

# Method 1: | operator (Python 3.9+)
merged1 = dict1 | dict2
print(f"\nUsing | : {merged1}")

# Method 2: {**dict1, **dict2} unpacking (Python 3.5+)
merged2 = {**dict1, **dict2}
print(f"Using unpacking: {merged2}")

# Method 3: update() method (modifies dict1)
dict1_copy = dict1.copy()
dict1_copy.update(dict2)
print(f"Using update(): {dict1_copy}")

# Method 4: With overlapping keys (later overwrites earlier)
merged_overlap = dict1 | dict3
print(f"\nMerge with overlap (dict1 | dict3): {merged_overlap}")

# Method 5: Using collections.ChainMap
from collections import ChainMap
merged_chain = dict(ChainMap(dict2, dict1))
print(f"Using ChainMap: {merged_chain}")

View the complete Dict programs page.

Program Console Merge two dictionaries (Python 3.9+ and older) Topic: PYTHON Vignaankosh.com
Execution Panel
Step 0/0
Console is empty.