Why dictionaries are used in Python - Performance Analysis
Start learning this pattern below
Jump into concepts and practice - no test required
We want to understand why dictionaries are chosen for certain tasks in Python.
How does using a dictionary affect the speed of finding or storing data?
Analyze the time complexity of the following code snippet.
my_dict = {"apple": 3, "banana": 5, "orange": 2}
# Access a value by key
value = my_dict["banana"]
# Add a new key-value pair
my_dict["grape"] = 7
# Check if a key exists
exists = "apple" in my_dict
# Remove a key-value pair
del my_dict["orange"]
This code shows common dictionary operations: accessing, adding, checking, and deleting items by key.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing or modifying items by key in the dictionary.
- How many times: Each operation happens once here, but in real use, these can happen many times.
When the dictionary grows bigger, how does the time to find or add a key change?
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1 step or less |
| 100 | About 1 step or less |
| 1000 | About 1 step or less |
Pattern observation: The time to find or add a key stays almost the same even if the dictionary gets bigger.
Time Complexity: O(1)
This means looking up or changing a value by key takes about the same short time no matter how many items are in the dictionary.
[X] Wrong: "Finding a value in a dictionary takes longer as the dictionary gets bigger."
[OK] Correct: Dictionaries use a special method that lets them find keys quickly without checking every item, so size does not slow them down much.
Knowing why dictionaries are fast helps you choose the right tool for storing and finding data quickly in real projects.
"What if we changed the dictionary keys to be lists instead of strings? How would the time complexity change?"
Practice
my_dict = {'name': 'Alice', 'age': 25}Solution
Step 1: Understand dictionary structure
Dictionaries store data as key-value pairs, where each key is unique.Step 2: Identify the main use
This structure allows quick access to values using keys, unlike lists which use indexes.Final Answer:
To store data with unique keys for quick access -> Option BQuick Check:
Dictionaries = unique keys + fast access [OK]
- Thinking dictionaries store data in order only
- Confusing dictionaries with lists for calculations
- Believing dictionaries create loops automatically
Solution
Step 1: Recognize dictionary syntax
Dictionaries use curly braces {} with key:value pairs separated by commas.Step 2: Compare options
my_dict = {'key1': 'value1', 'key2': 'value2'} uses correct syntax with braces and colons; others use lists, tuples, or invalid syntax.Final Answer:
my_dict = {'key1': 'value1', 'key2': 'value2'} -> Option CQuick Check:
Curly braces + key:value pairs = dictionary [OK]
- Using square brackets instead of curly braces
- Using tuples instead of dictionaries
- Missing curly braces or colons
phone_book = {'Alice': '1234', 'Bob': '5678'}
print(phone_book['Bob'])Solution
Step 1: Understand dictionary key access
Accessing phone_book['Bob'] retrieves the value for key 'Bob'.Step 2: Find the value for 'Bob'
In the dictionary, 'Bob' maps to '5678'.Final Answer:
5678 -> Option AQuick Check:
phone_book['Bob'] = '5678' [OK]
- Confusing keys and values
- Expecting the key name as output
- Mistyping key causing KeyError
contacts = {'John': '1111'}
contacts.add('Mary', '2222')Solution
Step 1: Check method used to add items
Dictionaries do not have an .add() method; items are added by assignment.Step 2: Correct way to add entry
Use contacts['Mary'] = '2222' to add a new key-value pair.Final Answer:
Using .add() method which does not exist for dictionaries -> Option DQuick Check:
Add items by assignment, not .add() [OK]
- Trying to use set methods on dictionaries
- Confusing dictionary syntax with list methods
- Assuming keys must be numbers
students = [('Anna', 85), ('Ben', 90), ('Anna', 95)]How can you create a dictionary that stores the highest score for each student?
Solution
Step 1: Understand the problem
We want one highest score per student, so duplicates must be checked.Step 2: Use a loop to update scores
Loop through the list, and for each student, update the dictionary only if the new score is higher than the current stored score.Final Answer:
Use a loop to update the dictionary only if the new score is higher -> Option AQuick Check:
Update dict with max score per key [OK]
- Using comprehension without checking scores
- Storing multiple scores instead of highest
- Using sets which don't map keys to values
