Python Dictionaries Deep Dive
A dictionary (dict) is an unordered (ordered since Python 3.7+), mutable collection of key-value pairs enclosed in curly braces ({key: value}).
- Keys must be Unique & Hashable: Keys must be immutable types (strings, numbers, tuples).
- Values can be Any Type: Lists, numbers, strings, or other nested dictionaries.
- Instant $O(1)$ Lookup: Implemented as a high-performance hash table in CPython.
# Creating a dictionary representing a developer profile:
developer = {
"name": "Balaji",
"role": "Python Backend Engineer",
"experience_years": 4,
"skills": ["Python", "FastAPI", "PostgreSQL", "Docker"],
"is_active": True
}
# Accessing dictionary values:
print("Developer Name:", developer["name"])
print("Role:", developer["role"])
print("Primary Skills:", developer["skills"])
When you access developer["name"], Python computes hash("name") and jumps directly to that memory slot in instantaneous $O(1)$ constant time.
Accessing a non-existent key with square brackets (dict["salary"]) causes a fatal KeyError crash. The .get() method returns None or a custom fallback safely:
user = {"id": 101, "username": "balaji_dev"}
# 1. Accessing existing key safely
print("User ID:", user.get("id"))
# 2. Accessing non-existent key with default fallback value
role = user.get("role", "Standard Member")
salary = user.get("salary", 0.0)
print("User Role:", role) # "Standard Member"
print("User Salary: Rs.", salary) # 0.0
Always use .get(key, fallback) when processing external JSON data from APIs where certain fields may be optional or missing.
Modify dictionary contents dynamically using assignment and removal methods:
dict[key] = new_value: Adds key if missing, or updates existing value.dict.update({...}): Merges multiple key-value pairs at once.dict.pop(key): Removes key and returns its value.del dict[key]: Deletes key from memory.
product = {"id": 501, "title": "Wireless Mouse", "price": 499}
print("Initial Product:", product)
# 1. Adding a new key-value pair
product["brand"] = "Logitech"
# 2. Updating an existing key
product["price"] = 449
# 3. Merging multiple fields with update()
product.update({"rating": 4.8, "in_stock": True})
print("After update:", product)
# 4. Removing a key with pop()
removed_rating = product.pop("rating")
print(f"Popped rating: {removed_rating} | Remaining keys: {list(product.keys())}")
Dictionary keys are case-sensitive: "Price" and "price" are treated as two separate distinct keys!
Iterate through dictionary contents cleanly using helper methods:
dict.keys(): Returns an iterable view of all keys.dict.values(): Returns an iterable view of all values.dict.items(): Returns(key, value)pairs for clean loop unpacking.
student_marks = {"Math": 95, "Physics": 88, "Chemistry": 92, "English": 85}
print("--- Subject & Marks Report ---")
for subject, marks in student_marks.items():
print(f"โข {subject:10}: {marks}/100")
# Calculate total marks from values:
total = sum(student_marks.values())
average = total / len(student_marks)
print(f"\nTotal Marks: {total} | Average: {average:.1f}%")
Always iterate with for key, val in d.items(): rather than manually calling d[key] inside the loop.
Construct and filter dictionaries in a single readable line using Dictionary Comprehensions:
# 1. Square numbers from 1 to 5:
squares_dict = {x: x ** 2 for x in range(1, 6)}
print("Squares Dict:", squares_dict)
# 2. Filter passing students (marks >= 50):
raw_marks = {"Alex": 45, "Balaji": 95, "Chloe": 78, "David": 35}
passed_students = {name: score for name, score in raw_marks.items() if score >= 50}
print("Passed Students (marks >= 50):", passed_students)
Dictionary comprehensions allow you to transform and filter data in a single step without verbose multi-line loops.
Dictionary keys MUST be immutable and hashable. Using a list as a key (e.g. {[1, 2]: "data"}) raises TypeError: unhashable type: 'list'. Use a tuple instead: {(1, 2): "data"}.
Create a dictionary of items in a shopping cart with their prices. Calculate the total bill and print items with prices greater than Rs. 100.
cart = {"Keyboard": 450, "Notebook": 80, "Mouse": 250, "Pen": 20}
total_bill = sum(cart.values())
expensive_items = {k: v for k, v in cart.items() if v > 100}
print("Shopping Cart:", cart)
print("Total Bill: Rs.", total_bill)
print("Items > Rs. 100:", expensive_items)
Q Are Python dictionaries ordered?
Yes. Since Python 3.7+, dictionaries officially preserve the exact insertion order of keys.
Q What is the time complexity of looking up a dictionary key?
Dictionary lookup runs in instantaneous O(1) average constant time due to hash table indexing.
Q Can a dictionary value be another dictionary?
Yes! Nested dictionaries are standard for modeling complex structured data like JSON documents.