Program Console Vignaankosh.com
Execution Panel
Console is empty.
Reverse key-value pairs (swap keys and values) 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.
# Reverse key-value pairs (swap keys and values)
original = {"first": "alpha", "second": "beta", "third": "alpha", "fourth": "gamma"}
print("Original:", original)
# Method 1: Dictionary comprehension (values become keys)
reversed_dict = {value: key for key, value in original.items()}
print("Reversed (loss of duplicate values):", reversed_dict)
# Method 2: Handle duplicate values by keeping last
reversed_dict2 = {}
for key, value in original.items():
reversed_dict2[value] = key
print("Manual reversal (last value wins):", reversed_dict2)
# Method 3: Handle duplicates by storing list of keys
reversed_with_list = {}
for key, value in original.items():
if value not in reversed_with_list:
reversed_with_list[value] = [key]
else:
reversed_with_list[value].append(key)
print("With duplicate handling (list):", reversed_with_list)
# Method 4: Using zip and dict
keys = list(original.keys())
values = list(original.values())
swapped = dict(zip(values, keys))
print("Using zip():", swapped)