Python 3 — Key-Value Pairs with Dictionaries & Sets

🐍 Python 3 🟢 Lesson 9 📅 July 2026

Sometimes lists aren't descriptive enough. If you want to store a user's profile information, looking up values by indices (like 'user[0]') gets confusing quickly. Dictionaries solve this by storing data in labeled Key-Value pairs, similar to a real word dictionary.

1 Python Dictionaries

Dictionaries are written inside curly braces ({}). Each entry consists of a unique **key** and its corresponding **value** separated by a colon (:):

Python 3 — Dictionaries ▶ Run Code
user = {
    "name": "Balaji",
    "role": "Developer",
    "is_active": True
}

# Accessing a value by its key label
print(user["name"]) # Balaji

# Adding a new key-value pair
user["location"] = "India"

# Modifying a value
user["is_active"] = False

print(user)
2 Iterating Over Dictionaries

You can loop through a dictionary to print keys, values, or both using the .items() method:

Python 3 — Dictionary Loops ▶ Run Code
prices = {"Apple": 0.99, "Orange": 1.25, "Milk": 2.50}

for item, price in prices.items():
    print(f"The price of {item} is \${price}")
3 Python Sets (Unique Elements)

A set is an unordered collection of elements with **no duplicate values**. They are written with curly braces too, but without colons. They are extremely fast for membership checks:

Python 3 — Sets ▶ Run Code
user_ids = {101, 102, 103, 101, 102}

# Duplicates are automatically removed
print(user_ids) # {101, 102, 103}

# Check if an item exists
print(101 in user_ids) # True
⚠️ KeyError Warning:

If you attempt to fetch a key that doesn't exist (like user["phone"]), Python will crash with a KeyError. To avoid this, use the .get() method, which returns None instead of crashing: user.get("phone").

4 Coding Challenge

Create a dictionary representing a book profile: title, author, and year published. Add a new key called 'rating', modify the publication year, and display each key-value pair on a separate line.