Python Dictionaries Deep Dive

๐Ÿ Python 3.12+ ๐ŸŸข Chapter 13 of 65 ๐Ÿ“‚ Phase 3: Strings and Collections ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: Key-Value Pairs ยท Hash Table Internals ยท CRUD ยท get() Fallback ยท Looping ยท Dict Comprehensions
Master Python dictionaries: hash table architecture, key-value mappings, safe access with get(), CRUD operations, looping (.items()), and dictionary comprehensions.
1What is a Dictionary? Key-Value Pair Architecture

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.
๐Ÿ’ป Example 1: Creating and Accessing Dictionaries
# 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"])
๐Ÿ” Hash Table Magic:

When you access developer["name"], Python computes hash("name") and jumps directly to that memory slot in instantaneous $O(1)$ constant time.

2Safe Access: Square Brackets [] vs .get(key, default)

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:

๐Ÿ’ป Example 2: Safe Key Access with .get()
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
๐Ÿ” Defensive Coding:

Always use .get(key, fallback) when processing external JSON data from APIs where certain fields may be optional or missing.

3Modifying Dictionaries (Adding, Updating, Deleting)

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.
๐Ÿ’ป Example 3: Adding, Updating, and Removing Dictionary Keys
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())}")
๐Ÿ” Mutation Note:

Dictionary keys are case-sensitive: "Price" and "price" are treated as two separate distinct keys!

4Looping Over Dictionaries (.keys(), .values(), .items())

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.
๐Ÿ’ป Example 4: Looping Through Dictionaries with .items()
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}%")
๐Ÿ” Best Practice:

Always iterate with for key, val in d.items(): rather than manually calling d[key] inside the loop.

5Dictionary Comprehensions ({k: v for ... in ...})

Construct and filter dictionaries in a single readable line using Dictionary Comprehensions:

๐Ÿ’ป Example 5: 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)
๐Ÿ” Comprehension Power:

Dictionary comprehensions allow you to transform and filter data in a single step without verbose multi-line loops.

โš ๏ธ Common Developer Pitfall: Using Unhashable Mutable Objects as Dictionary Keys

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"}.

๐Ÿ’ป Hands-on Interactive Practice Challenge

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.

Python 3 Practice Challenge โ–ถ Run in Compiler
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)
Run This Challenge in Online Python IDE โ†’
โ“ Frequently Asked Questions (FAQ)

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.

OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on Python 3.12+ runtime ยท Last updated August 2026