Dictionaries in Python
# Dictionaries in Python
Welcome to Chapter 12! Dictionaries are Python's most powerful built-in data structure. They store data as key-value pairs, making data lookup lightning fast.
---
1. Learning Objectives
- Create and manipulate dictionaries.
- Use dictionary methods.
- Work with nested dictionaries.
- Write dictionary comprehensions.
- Build a student database system.
---
2. Creating Dictionaries
```python id="py12ex1" # Different ways to create dictionaries student = {"name": "Alice", "age": 25, "grade": "A"} empty = {} fromconstructor = dict(name="Bob", age=30) from_pairs = dict([("x", 1), ("y", 2)])
print(student) print(student["name"]) # Alice
python id="py12_ex2" user = {"name": "Alice", "age": 25, "city": "NYC"}
# Access print(user["name"]) # Alice print(user.get("email")) # None (no error) print(user.get("email", "N/A")) # N/A (default value)
# Modify user["age"] = 26 # Update user["email"] = "a@b.com" # Add new key
# Remove del user["city"] removed = user.pop("email") print(user)
python id="py12ex3" data = {"a": 1, "b": 2, "c": 3}
print(data.keys()) # dictkeys(['a', 'b', 'c']) print(data.values()) # dictvalues([1, 2, 3]) print(data.items()) # dictitems([('a', 1), ('b', 2), ('c', 3)])
# Iteration for key, value in data.items(): print(f" {key}: {value}")
# setdefault — get value or set default if missing count = {} for char in "hello": count[char] = count.get(char, 0) + 1 print(count) # {'h': 1, 'e': 1, 'l': 2, 'o': 1}
# update — merge dictionaries defaults = {"color": "blue", "size": "M"} custom = {"color": "red"} defaults.update(custom) print(defaults) # {'color': 'red', 'size': 'M'}
# Merge operator (Python 3.9+) merged = defaults | custom
python id="py12_ex4" # Squares dictionary squares = {x: x**2 for x in range(1, 6)} print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Filter with condition scores = {"Alice": 85, "Bob": 62, "Charlie": 91, "Diana": 45} passed = {k: v for k, v in scores.items() if v >= 60} print(passed) # {'Alice': 85, 'Bob': 62, 'Charlie': 91}
# Swap keys and values flipped = {v: k for k, v in scores.items()} print(flipped)
python id="py12_ex5" school = { "student1": {"name": "Alice", "grade": "A", "gpa": 3.9}, "student2": {"name": "Bob", "grade": "B", "gpa": 3.5}, "student3": {"name": "Charlie", "grade": "A", "gpa": 3.8} }
# Access nested values print(school["student1"]["name"]) # Alice print(school["student2"]["gpa"]) # 3.5
# Iterate nested dict for sid, info in school.items(): print(f" {info['name']}: Grade {info['grade']}, GPA {info['gpa']}")
python id="py12project" students = {}
print("=" * 45) print(" 🎓 STUDENT DATABASE SYSTEM") print("=" * 45)
while True:
print("\n 1. Add Student")
print(" 2. View All Students")
print(" 3. Search Student")
print(" 4. Delete Student")
print(" 5. Exit")
choice = input("\n Choose (1-5): ")
if choice == "1":
sid = input(" Student ID: ")
name = input(" Name: ")
grade = input(" Grade: ")
gpa = float(input(" GPA: "))
students[sid] = {"name": name, "grade": grade, "gpa": gpa}
print(f" ✅ {name} added!")
elif choice == "2":
if not students:
print(" 📭 No students yet!")
else:
print(f"\n {'ID':<8}{'Name':<15}{'Grade':<8}{'GPA':<6}")
print(" " + "-" * 37)
for sid, info in students.items():
print(f" {sid:<8}{info['name']:<15}{info['grade']:<8}{info['gpa']:<6}")
elif choice == "3":
sid = input(" Enter Student ID: ")
if sid in students:
info = students[sid]
print(f" Name: {info['name']}, Grade: {info['grade']}, GPA: {info['gpa']}")
else:
print(" ❌ Student not found!")
elif choice == "4":
sid = input(" Enter Student ID: ")
if sid in students:
removed = students.pop(sid)
print(f" 🗑️ {removed['name']} removed!")
else:
print(" ❌ Student not found!")
elif choice == "5":
print(" 👋 Goodbye!")
break
``
---
8. Common Mistakes
-
1.
KeyError: Accessing a non-existent key. Use .get()
instead.
- 2. Mutable keys: Lists can't be dict keys (use tuples).
- 3. Modifying dict during iteration: Iterate over a copy.
-
4.
Using {}
for empty set:{}creates an empty dict, not set.
---
9. MCQs with Answers
Q1: Dicts are: A) Ordered and mutable B) Unordered and immutable C) Ordered and immutable D) Unordered and mutable Answer: A — Since Python 3.7+, dicts maintain insertion order.
Q2: d.get("key") when key missing returns:
A) Error B) None C) 0 D) False
Answer: B
Q3: Which can be a dict key? A) List B) Set C) Tuple D) Dict Answer: C — Only hashable/immutable types.
Q4: d.items() returns:
A) Keys B) Values C) Key-value pairs D) Indices
Answer: C
Q5: {x: x2 for x in range(3)} returns:
A) {0, 1, 4} B) {0:0, 1:1, 2:4} C) [0, 1, 4] D) Error
Answer: B
Q6: Merge operator for dicts (3.9+): A) + B) & C) | D) * Answer: C
Q7: "key" in dict checks:
A) Keys B) Values C) Both D) Items
Answer: A
Q8: dict.pop("key") does:
A) Returns value only B) Removes and returns value C) Removes key only D) Error
Answer: B
Q9: len({"a":1, "b":2}) returns:
A) 4 B) 2 C) 3 D) 1
Answer: B
Q10: dict.update() does:
A) Creates new dict B) Merges into existing dict C) Sorts dict D) Filters dict
Answer: B
---
10. Interview Questions
- 1. Are dicts ordered in Python 3.7+? Yes, they maintain insertion order.
- 2. Time complexity of dict operations? O(1) average for get, set, delete.
- 3. defaultdict vs regular dict? defaultdict auto-initializes missing keys with a factory function.
-
4.
How to sort a dict by values? sorted(d.items(), key=lambda x: x[1])
.
-
5.
What is OrderedDict? Dict that remembers insertion order (now redundant since 3.7+, but has moveto_end()
).
---
11. Summary
- Dictionaries store key-value pairs with O(1) lookup.
-
Use .get()
for safe access,.items()` for iteration.
- Dict comprehensions create dicts concisely.
- Nested dicts model complex, hierarchical data.
- Keys must be hashable (immutable).
---
12. Next Chapter Recommendation
In Chapter 13: Functions in Python**, you'll learn to write reusable, organized code with functions! 🚀