Dictionaries: Key-Value Mapping
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A dictionary (dict) is an unordered-by-nature (insertion-ordered in Python 3.7+) collection of key-value pairs. Dictionaries provide average O(1) constant-time lookups.
Creating dictionaries
Dictionary is a collection that stores data as key-value pairs. You look up a value by its key, not by a position number, and the lookup stays fast even for a very large dictionary.
Enclose key-value pairs separated by colons : inside curly braces {}.
student = { "id": 101, "name": "Kabir", "gpa": 3.9}print(student["name"])Accessing student["name"] retrieves 'Kabir' instantly in O(1) time.
Safe lookups with get()
KeyError is the error Python raises when you ask a dictionary for a key that is not in it. The method get() avoids it by returning a fallback value instead.
Accessing a missing key with square brackets raises a KeyError. The .get() method returns None or a custom fallback instead.
config = {"port": 8000, "debug": True}print(config.get("host", "127.0.0.1"))print(config.get("timeout"))Example 1 · Selling one unit
product = {"sku": "SKU-99", "price": 450, "stock": 12}# Check inventoryif product.get("stock", 0) > 0: product["stock"] -= 1 print(f"Purchased 1 unit. Remaining: {product['stock']}")Purchased 1 unit. Remaining: 11
What this code does
- Uses
.get('stock', 0)to inspect inventory safely. - Deducts 1 unit from stock, printing remaining count 11.
Because 'host' was not found, .get() smoothly returns the default '127.0.0.1'.
Adding and updating keys
Assigning to a key adds it if it does not exist, or updates its value if it does.
user = {"name": "Tara"}user["role"] = "Developer"user["role"] = "Lead"print(user)Example 2 · Updating an order record
order = {"id": 5012, "status": "packed"}order["status"] = "shipped"order["courier"] = "Express"print(order)print(len(order)){'id': 5012, 'status': 'shipped', 'courier': 'Express'}
3What this code does
order["status"]already exists, so the assignment replaces"packed"with"shipped".order["courier"]is a new key, so the assignment adds it at the end.len(order)counts the keys: three.
user['role'] = 'Developer' inserts the new key, and assigning 'Lead' updates it in place.
Checking keys and removing entries
Hashable is a value whose hash code never changes while it lives, so Python can use it as a dictionary key. Strings, numbers and tuples of them are hashable. Lists and dictionaries are not.
The in operator checks whether a key exists. The method pop() removes a key and gives back its value, and del removes a key without returning it.
stock = {"pen": 40, "book": 12, "bag": 7}print("pen" in stock)removed = stock.pop("book")del stock["bag"]print(removed, stock, len(stock))Example 3 · Cancelling a cart line
cart = {"laptop": 1, "mouse": 2, "cable": 3}removed = cart.pop("cable")print(f"Removed {removed} cables")print("cable" in cart)print(cart.pop("hub", 0))print(cart)Removed 3 cables
False
0
{'laptop': 1, 'mouse': 2}What this code does
pop("cable")deletes the key and returns its value, 3.- After that
"cable" in cartis False. pop("hub", 0)gives the fallback 0 becausehubis not there. Without a fallback it would raise a KeyError.
in looks only at keys. pop returned 12 and del returned nothing, so stock is left with the one key pen.
Next step
Check your understanding
9 quick questions