Lab 05: Dictionaries

🎯 Objective

Master Python dictionaries β€” the key-value store used in JSON, config files, caching, and almost every real Python application.

πŸ“š Background

Dictionaries store key-value pairs with O(1) average lookup. Python 3.7+ dicts maintain insertion order. JSON maps directly to Python dicts β€” making them essential for web APIs. The collections module extends dicts with Counter and defaultdict.

⏱️ Estimated Time

30 minutes

πŸ“‹ Prerequisites

  • Lab 4: Lists, Tuples & Sets

πŸ› οΈ Tools Used

  • Python 3.12

πŸ”¬ Lab Instructions

Step 1: Creating Dictionaries

πŸ“Έ Verified Output:

Step 2: Access and Modification

πŸ“Έ Verified Output:

Step 3: Iterating Dictionaries

πŸ“Έ Verified Output:

Step 4: Merging Dictionaries

πŸ“Έ Verified Output:

Step 5: Dictionary Comprehensions

πŸ“Έ Verified Output:

Step 6: Nested Dictionaries

πŸ“Έ Verified Output:

Step 7: Counter and defaultdict

πŸ“Έ Verified Output:

Step 8: Dict as JSON

πŸ“Έ Verified Output:

βœ… Verification

Expected output:

🚨 Common Mistakes

  • d["missing"] raises KeyError β€” use d.get("key", default) for safe access

  • Modifying dict while iterating β†’ RuntimeError β€” iterate list(d.keys())

  • Dict keys must be hashable β€” lists can't be keys, but tuples can

  • dict.update() modifies in place; d | other returns new dict (Python 3.9+)

πŸ“ Summary

  • Dicts: key-value pairs with O(1) lookup; ordered since Python 3.7

  • Safe access: .get(key, default); existence check: key in d

  • Iterate: .items(), .keys(), .values()

  • Dict comprehensions: {k: v for k, v in iterable}

  • Counter for counting, defaultdict for grouping

πŸ”— Further Reading

Last updated