Neural Sync Active
Dictionaries — Key-Value Pairs
Registry Synced
Dictionaries — Key-Value Pairs
811 words
4 min read
Reading compass
Now · 🎯 Learning Objectives
Dictionaries — Key-Value Pairs
Why read this? A list stores values by position (0, 1, 2...). A dictionary stores values by KEY — like a real dictionary where you look up a word (key) to find its definition (value). This is the most natural way to represent real-world data: "Alice → 85", "Paris → France", "A → 10".
🎯 Learning Objectives
By the end of this topic, you will be able to:
- Create dictionaries with
{}anddict() - Access, add, modify, and delete key-value pairs
- Iterate over keys, values, and items
- Use
get()for safe access - Use dictionaries for counting, grouping, and lookups
📋 Prerequisites
- Understanding of lists and tuples.
- Sets for understanding hashability.
📖 Core Content
19.1 What Problem Do Dictionaries Solve?
Intuition: A phone book. You look up "Alice" (key) and get "123-456" (value). You don't care where in the book Alice's entry is — you just want fast lookup by name. Dictionaries give you O(1) average lookup speed.
19.2 Creating Dictionaries
python# runnable # Curly braces with key:value pairs student = { "name": "Alice", "age": 25, "grade": "A" } print(student) # Using dict() constructor person = dict(name="Bob", age=30, city="New York") print(person) # From pairs pairs = [("one", 1), ("two", 2), ("three", 3)] d = dict(pairs) print(d) # Empty dict empty = {}
19.3 Accessing and Modifying
python# runnable student = {"name": "Alice", "age": 25, "grade": "A"} # Access by key print(student["name"]) # Alice print(student["age"]) # 25 # Access with get (safe: returns None or default if missing) print(student.get("grade")) # A print(student.get("city")) # None print(student.get("city", "N/A")) # N/A (default value) # Add/Modify student["city"] = "New York" # add new key student["age"] = 26 # modify existing print(student) # Delete del student["grade"] print(student) # Pop (remove and return) city = student.pop("city") print(f"Removed: {city}, Remaining: {student}")
19.4 Dictionary Methods
python# runnable d = {"a": 1, "b": 2, "c": 3} # Keys, values, items print("Keys:", list(d.keys())) print("Values:", list(d.values())) print("Items:", list(d.items())) # Iterate for key in d: # same as d.keys() print(key, d[key]) for key, value in d.items(): print(f"{key} → {value}") # Check key existence print("a" in d) # True print("z" in d) # False
19.5 Worked Example 1: Word Frequency Counter
python# runnable text = "the cat in the hat wore the hat" words = text.split() freq = {} for word in words: if word in freq: freq[word] += 1 else: freq[word] = 1 print(freq) # Alternative using get(): freq2 = {} for word in words: freq2[word] = freq2.get(word, 0) + 1 print(freq2)
19.6 Worked Example 2: Grade Book
python# runnable grades = { "Alice": [85, 92, 78], "Bob": [70, 65, 80], "Charlie": [95, 88, 91] } for student, scores in grades.items(): avg = sum(scores) / len(scores) print(f"{student}: {avg:.1f}%")
19.7 Worked Example 3: Phone Book
python# runnable phonebook = {} while True: name = input("Name (or 'quit'): ") if name == 'quit': break phone = input("Phone: ") phonebook[name] = phone # Lookup search = input("\nSearch name: ") print(phonebook.get(search, "Not found"))
19.8 Dictionary Comprehensions
python# runnable # Square numbers as dict squares = {x: x**2 for x in range(10)} print(squares) # Filter even_squares = {x: x**2 for x in range(10) if x % 2 == 0} print(even_squares) # Swap keys and values original = {"a": 1, "b": 2, "c": 3} swapped = {v: k for k, v in original.items()} print(swapped)
⚠️ Common Pitfalls
Pitfall 1: KeyError When Key Missing
The mistake:
d["missing_key"] when key doesn't exist. Error: KeyError: 'missing_key' Fix: Use d.get("missing_key", default) or check if "key" in d:.Pitfall 2: Mutable Keys (Lists as Keys)
The mistake: Using a list as a dictionary key. Error:
TypeError: unhashable type: 'list' Fix: Use tuples instead: {(1, 2): "point"}.Pitfall 3: Modifying Dict While Iterating
The mistake: Adding/removing keys while iterating over a dict. Error:
RuntimeError: dictionary changed size during iteration Fix: Iterate over a copy: for k in list(d.keys()):.📝 Practice Questions
Q1: What does this output?pythond = {"a": 1, "b": 2} print(d.get("c", 0))Answer:0(default value returned since "c" doesn't exist) Q2: Write a dict comprehension that maps numbers 1-5 to their cubes.Answer:{x: x**3 for x in range(1, 6)}Q3-10: Additional dictionary questions.(Following pattern with answers.)
🔗 Cross-References
- Next Topic: Dictionary Operations & Advanced
- Previous Topic: Strings Advanced
- BSCS2002 PDSA: Dictionaries are implemented as hash tables — O(1) average lookup.
- Reference: Python for Everybody, Chapter 9 — "Dictionaries"
- Video: L55: Dictionaries efficient data storage, L59: More on dictionaries Join Discord Previous18. Strings AdvancedNext20. Dict Operations