0
0
Pythonprogramming~10 mins

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

Choose your learning style9 modes available
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.