► Understanding Dictionaries
Dictionaries store data in key-value pairs, allowing fast lookup by key. They’re like real-world dictionaries where you look up a word (key) to find its definition (value).
► Real-World Analogy
Think of dictionaries like a phone book:
» Each name (key) maps to a phone number (value)
» You search by name to quickly find the number
» Each name is unique, just like dictionary keys
» You can add, update, or remove entries
» Much faster than checking each entry in a list
► Key Concepts
✓ Key-value pairs: Each key maps to one value
✓ Unique keys: No duplicate keys allowed
✓ Mutable: Can add, modify, delete entries
✓ Fast lookup: O(1) average time complexity
✓ Curly braces: Created with {}
■ Code Examples
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# Creating dictionaries student = {"name": "Alice", "age": 20, "grade": "A"} prices = {"apple": 0.5, "banana": 0.3, "orange": 0.6} empty_dict = {} print(student) print(f"Name: {student['name']}") # Adding and updating student["email"] = "alice@example.com" student["age"] = 21 print(f"Updated: {student}") # Dictionary methods print(f"Keys: {student.keys()}") print(f"Values: {student.values()}") print(f"Items: {student.items()}") # Get method with default phone = student.get("phone", "Not found") print(f"Phone: {phone}") # Removing items removed = student.pop("email") print(f"After removing email: {student}") |
