Adding and updating key-value pairs in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we add or update key-value pairs in a dictionary, we want to know how the time it takes changes as the dictionary grows.
We ask: How does the work grow when the dictionary gets bigger?
Analyze the time complexity of the following code snippet.
my_dict = {}
for i in range(n):
my_dict[i] = i * 2
my_dict[5] = 100
This code adds n key-value pairs to an empty dictionary, then updates the value for key 5.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding or updating a key-value pair in the dictionary inside the loop.
- How many times: The loop runs n times, so the add/update happens n times.
Each time we add or update a key, the work is about the same, no matter how big the dictionary is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 adds/updates |
| 100 | About 100 adds/updates |
| 1000 | About 1000 adds/updates |
Pattern observation: The total work grows directly with n, because each add/update takes roughly the same time.
Time Complexity: O(n)
This means the time to add or update n items grows in a straight line with n.
[X] Wrong: "Adding or updating a key takes longer as the dictionary gets bigger because it has to search through all keys."
[OK] Correct: Dictionaries use a special method that lets them find keys quickly without checking every item, so each add or update takes about the same time no matter the size.
Understanding how adding and updating dictionary entries scales helps you explain how your code handles data efficiently, a skill useful in many programming tasks.
"What if we used a list of pairs instead of a dictionary? How would the time complexity change when adding or updating values?"
Practice
dictionary[key] = value in Python if the key already exists?Solution
Step 1: Understand dictionary key assignment
Usingdictionary[key] = valuesets the value for the given key.Step 2: Behavior when key exists
If the key exists, the old value is replaced with the new one.Final Answer:
The value for that key is updated to the new value. -> Option BQuick Check:
Assigning existing key updates value [OK]
- Thinking it adds a duplicate key
- Expecting an error on existing key
- Assuming dictionary clears automatically
'color': 'blue' to a dictionary named car?Solution
Step 1: Recall dictionary syntax for adding pairs
Usedictionary[key] = valueto add or update pairs.Step 2: Check each option
car['color'] = 'blue' uses correct syntax:car['color'] = 'blue'.Final Answer:
car['color'] = 'blue' -> Option DQuick Check:
Use square brackets for keys [OK]
- Using parentheses instead of brackets
- Trying to call add() method which doesn't exist
- Using dot notation which works only for objects
fruit_colors = {'apple': 'red', 'banana': 'yellow'}
fruit_colors['banana'] = 'green'
fruit_colors['cherry'] = 'red'
print(fruit_colors)Solution
Step 1: Update existing key 'banana'
The value for 'banana' changes from 'yellow' to 'green'.Step 2: Add new key 'cherry'
The pair 'cherry': 'red' is added to the dictionary.Final Answer:
{'apple': 'red', 'banana': 'green', 'cherry': 'red'} -> Option CQuick Check:
Update and add keys correctly [OK]
- Assuming old value stays after update
- Forgetting to add new key
- Expecting syntax error from valid code
data = {'x': 1, 'y': 2}
data['z'] == 3
print(data)Solution
Step 1: Identify the operator used for assignment
The code uses '==' which is a comparison operator, not assignment.Step 2: Correct operator for adding/updating dictionary
Use '=' to assign value to a key in dictionary.Final Answer:
Using '==' instead of '=' to add/update key-value pair. -> Option AQuick Check:
Use '=' to assign values [OK]
- Confusing '==' with '='
- Thinking keys must be numbers
- Believing print can't show dictionaries
inventory = {'apple': 5, 'banana': 3}. You want to add 2 more apples to the count. Which code correctly updates the inventory?Solution
Step 1: Understand ways to update dictionary values
You can update a value by direct assignment, augmented assignment, or using update() method.Step 2: Check each option
inventory['apple'] = inventory['apple'] + 2 adds 2 and assigns directly. inventory['apple'] += 2 uses += operator. inventory.update({'apple': inventory['apple'] + 2}) uses update() with new value.Step 3: Confirm all methods work
All three correctly increase 'apple' count by 2.Final Answer:
All of the above -> Option AQuick Check:
Multiple ways to update dictionary values [OK]
- Thinking only one method works
- Forgetting to add current value before assignment
- Using update() incorrectly without new value
