Dictionaries and Key-Value Operations
Dictionaries are Python's implementation of hash maps, allowing you to store and retrieve data by meaningful keys rather than numeric indices.
What is it?
A Python `dict` is an ordered (as of Python 3.7+), mutable collection of key-value pairs written as `{key: value}`.
Why is it used?
Stores structured entity models like user accounts, course data, settings configs, and JSON payloads.
Detailed Explanation
Dictionary Methods:
• Accessing:
• `d[key]`: Throws `KeyError` if key is missing.
• `d.get(key, default)`: Safely returns default value if key is missing (prevents crashes!).
• Modifying:
• `d[key] = value`: Updates existing or inserts new pair.
• `d.update({k: v})`: Merges another dictionary.
• `d.pop(key)`: Removes key and returns its value.
• Iteration:
• `for key in d:` (keys)
• `for key, val in d.items():` (both keys and values)
Syntax Structure
Syntax Blueprint
student = {"name": "Aniket", "course": "Python"}
role = student.get("role", "user")
Code Example
PYTHON Code
# Course Configuration Model
course_info = {
"name": "KLiC Certificate in Advanced Python",
"slug": "klic-advanced-python",
"price": 2500,
"duration": "2.5 Months",
"modules": ["OOP", "Flask", "Data Pipelines", "Automation"],
"is_active": True
}
# Safe access with .get()
certification = course_info.get("certification", "MKCL Certified")
print(f"Course: {course_info['name']}")
print(f"Certification: {certification}")
# Updating dictionary
course_info["enrollment_count"] = 120
# Iterating with .items()
print("\n=== Course Summary ===")
for key, value in course_info.items():
if key == "modules":
print(f"{key.title()}: {', '.join(value)}")
else:
print(f"{key.title()}: {value}")
Explanation of the Code
• `.get("certification", "...")` returns the default string without raising a `KeyError`.
• Iterates through key-value pairs with `.items()`.
Expected Output
Course: KLiC Certificate in Advanced Python
Certification: MKCL Certified
=== Course Summary ===
Name: KLiC Certificate in Advanced Python
Slug: klic-advanced-python
Price: 2500
Duration: 2.5 Months
Modules: OOP, Flask, Data Pipelines, Automation
Is_Active: True
Enrollment_Count: 120
Real-World Application
Every REST API returns JSON data which converts directly into Python dictionaries.
Common Mistakes to Avoid
• Accessing missing keys with square brackets `dict['missing']`, crashing the program with `KeyError`. Always prefer `dict.get('missing', default)`.
• Using mutable lists as dictionary keys (keys must be immutable/hashable).
Quick Practice Challenge
Create a dictionary with keys 'title', 'price', and 'discount'. Safely read a 'coupon' key with default None.
Key Takeaways
• Dictionaries store associative key-value mappings.
• Always use `.get(key, default)` to avoid `KeyError` crashes.
• Iterate through keys and values together using `.items()`.