Python 3 — Key-Value Pairs with Dictionaries & Sets
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.
Dictionaries are written inside curly braces ({}). Each entry consists of a unique **key** and its corresponding **value** separated by a colon (:):
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)
You can loop through a dictionary to print keys, values, or both using the .items() method:
prices = {"Apple": 0.99, "Orange": 1.25, "Milk": 2.50}
for item, price in prices.items():
print(f"The price of {item} is \${price}")
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:
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
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").
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.