Bird
Raised Fist0
Pythonprogramming~10 mins

Adding and updating key-value pairs in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Adding and updating key-value pairs
Start with dictionary
Add new key-value pair?
YesAdd key and value
Update existing key's value
Dictionary updated
End
Start with a dictionary, then add a new key-value pair or update an existing key's value, resulting in an updated dictionary.
Execution Sample
Python
my_dict = {'a': 1, 'b': 2}
my_dict['c'] = 3
my_dict['a'] = 4
print(my_dict)
This code adds a new key 'c' with value 3 and updates the value of existing key 'a' to 4.
Execution Table
StepActionDictionary StateOutput
1Initialize dictionary{'a': 1, 'b': 2}
2Add key 'c' with value 3{'a': 1, 'b': 2, 'c': 3}
3Update key 'a' to value 4{'a': 4, 'b': 2, 'c': 3}
4Print dictionary{'a': 4, 'b': 2, 'c': 3}{'a': 4, 'b': 2, 'c': 3}
💡 All steps executed; dictionary updated and printed.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
my_dict{'a': 1, 'b': 2}{'a': 1, 'b': 2, 'c': 3}{'a': 4, 'b': 2, 'c': 3}{'a': 4, 'b': 2, 'c': 3}
Key Moments - 2 Insights
Why does updating an existing key overwrite its old value instead of adding a new key?
Because dictionary keys are unique, assigning a value to an existing key replaces the old value, as shown in step 3 of the execution_table.
What happens if we add a key that wasn't in the dictionary before?
A new key-value pair is added to the dictionary, increasing its size, as seen in step 2 where key 'c' is added.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the dictionary state after step 2?
A{'a': 4, 'b': 2, 'c': 3}
B{'a': 1, 'b': 2, 'c': 3}
C{'a': 1, 'b': 2}
D{'a': 1, 'b': 2, 'a': 4}
💡 Hint
Check the 'Dictionary State' column in row for step 2 in execution_table.
At which step does the value of key 'a' change?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the 'Action' and 'Dictionary State' columns in execution_table for step 3.
If we add a new key 'd' with value 5 after step 3, what will be the final dictionary?
A{'a': 4, 'b': 2, 'd': 5}
B{'a': 1, 'b': 2, 'c': 3, 'd': 5}
C{'a': 4, 'b': 2, 'c': 3, 'd': 5}
D{'a': 4, 'b': 2, 'c': 3}
💡 Hint
Adding a new key adds it to the dictionary without removing existing keys, see step 2 for similar action.
Concept Snapshot
Adding and updating key-value pairs in a dictionary:
- Use dict[key] = value
- If key is new, pair is added
- If key exists, value is updated
- Keys are unique
- Dictionary changes immediately
Full Transcript
We start with a dictionary containing keys 'a' and 'b'. Then we add a new key 'c' with value 3, which adds a new pair. Next, we update the value of existing key 'a' to 4, replacing the old value. Finally, we print the dictionary showing all changes. This shows how to add new pairs and update existing ones in Python dictionaries.

Practice

(1/5)
1. What happens when you use dictionary[key] = value in Python if the key already exists?
easy
A. A new key-value pair is added without changing the old one.
B. The value for that key is updated to the new value.
C. An error is raised because the key already exists.
D. The dictionary is cleared before adding the new pair.

Solution

  1. Step 1: Understand dictionary key assignment

    Using dictionary[key] = value sets the value for the given key.
  2. Step 2: Behavior when key exists

    If the key exists, the old value is replaced with the new one.
  3. Final Answer:

    The value for that key is updated to the new value. -> Option B
  4. Quick Check:

    Assigning existing key updates value [OK]
Hint: Assigning to existing key updates value, no error [OK]
Common Mistakes:
  • Thinking it adds a duplicate key
  • Expecting an error on existing key
  • Assuming dictionary clears automatically
2. Which of the following is the correct syntax to add a new key-value pair 'color': 'blue' to a dictionary named car?
easy
A. car.color = 'blue'
B. car.add('color', 'blue')
C. car('color') = 'blue'
D. car['color'] = 'blue'

Solution

  1. Step 1: Recall dictionary syntax for adding pairs

    Use dictionary[key] = value to add or update pairs.
  2. Step 2: Check each option

    car['color'] = 'blue' uses correct syntax: car['color'] = 'blue'.
  3. Final Answer:

    car['color'] = 'blue' -> Option D
  4. Quick Check:

    Use square brackets for keys [OK]
Hint: Use square brackets and equals sign to add/update [OK]
Common Mistakes:
  • Using parentheses instead of brackets
  • Trying to call add() method which doesn't exist
  • Using dot notation which works only for objects
3. What is the output of this code?
fruit_colors = {'apple': 'red', 'banana': 'yellow'}
fruit_colors['banana'] = 'green'
fruit_colors['cherry'] = 'red'
print(fruit_colors)
medium
A. {'apple': 'red', 'banana': 'yellow', 'cherry': 'red'}
B. {'apple': 'red', 'banana': 'green'}
C. {'apple': 'red', 'banana': 'green', 'cherry': 'red'}
D. SyntaxError

Solution

  1. Step 1: Update existing key 'banana'

    The value for 'banana' changes from 'yellow' to 'green'.
  2. Step 2: Add new key 'cherry'

    The pair 'cherry': 'red' is added to the dictionary.
  3. Final Answer:

    {'apple': 'red', 'banana': 'green', 'cherry': 'red'} -> Option C
  4. Quick Check:

    Update and add keys correctly [OK]
Hint: Updating key changes value; new key adds pair [OK]
Common Mistakes:
  • Assuming old value stays after update
  • Forgetting to add new key
  • Expecting syntax error from valid code
4. Find the error in this code snippet:
data = {'x': 1, 'y': 2}
data['z'] == 3
print(data)
medium
A. Using '==' instead of '=' to add/update key-value pair.
B. Missing quotes around key 'z'.
C. Dictionary keys must be integers, not strings.
D. print() cannot display dictionaries.

Solution

  1. Step 1: Identify the operator used for assignment

    The code uses '==' which is a comparison operator, not assignment.
  2. Step 2: Correct operator for adding/updating dictionary

    Use '=' to assign value to a key in dictionary.
  3. Final Answer:

    Using '==' instead of '=' to add/update key-value pair. -> Option A
  4. Quick Check:

    Use '=' to assign values [OK]
Hint: Use single '=' to assign, not '==' [OK]
Common Mistakes:
  • Confusing '==' with '='
  • Thinking keys must be numbers
  • Believing print can't show dictionaries
5. You have a dictionary inventory = {'apple': 5, 'banana': 3}. You want to add 2 more apples to the count. Which code correctly updates the inventory?
hard
A. All of the above
B. inventory['apple'] += 2
C. inventory.update({'apple': inventory['apple'] + 2})
D. inventory['apple'] = inventory['apple'] + 2

Solution

  1. Step 1: Understand ways to update dictionary values

    You can update a value by direct assignment, augmented assignment, or using update() method.
  2. 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.
  3. Step 3: Confirm all methods work

    All three correctly increase 'apple' count by 2.
  4. Final Answer:

    All of the above -> Option A
  5. Quick Check:

    Multiple ways to update dictionary values [OK]
Hint: Multiple ways to update values, use any [OK]
Common Mistakes:
  • Thinking only one method works
  • Forgetting to add current value before assignment
  • Using update() incorrectly without new value