Skip to content

ENUMERATE WITH DICTIONARIES

Python
#!/usr/bin/env python3
"""
ENUMERATE WITH DICTIONARIES
Track positions while building dictionaries
"""

print("=== Create Index-to-Value Dictionary ===")
colors = ["red", "green", "blue", "yellow"]

color_dict = {i: color for i, color in enumerate(colors)}
print(f"Color dict: {color_dict}")

print("\n=== Create Value-to-Index Dictionary (Reverse Lookup) ===")
reverse_lookup = {color: i for i, color in enumerate(colors)}
print(f"Reverse lookup: {reverse_lookup}")
print(f"Index of 'blue': {reverse_lookup['blue']}")

print("\n=== Numbered Menu System ===")
menu_items = ["New File", "Open File", "Save", "Exit"]

menu = {}
for i, item in enumerate(menu_items, start=1):
    menu[i] = item
    print(f"{i}. {item}")

print(f"\nMenu dictionary: {menu}")

print("\n=== Track Changes in List ===")
before = ["apple", "banana", "cherry"]
after = ["apple", "orange", "cherry"]

print("Changes detected:")
for i, (old, new) in enumerate(zip(before, after)):
    if old != new:
        print(f"  Position {i}: '{old}' changed to '{new}'")
    else:
        print(f"  Position {i}: '{old}' unchanged")