Recall & Review
beginner
How do you add a new key-value pair to a Python dictionary?
You add a new key-value pair by assigning a value to a new key using square brackets. For example:
my_dict['new_key'] = 'new_value'.Click to reveal answer
beginner
What happens if you assign a value to an existing key in a Python dictionary?
The existing key's value is updated (replaced) with the new value. For example,
my_dict['key'] = 'new_value' changes the old value to 'new_value'.Click to reveal answer
intermediate
Show how to add multiple key-value pairs to a dictionary at once.
Use the
update() method with another dictionary or iterable of pairs. Example: my_dict.update({'a': 1, 'b': 2}) adds or updates keys 'a' and 'b'.Click to reveal answer
intermediate
Can you use the
setdefault() method to add a key-value pair? How?Yes.
setdefault(key, default_value) adds the key with default_value if the key is not present. If the key exists, it returns its value without changing it.Click to reveal answer
intermediate
What is the difference between adding a key-value pair using assignment and using
update()?Assignment adds or updates a single key-value pair:
my_dict[key] = value. update() can add or update multiple pairs at once from another dictionary or iterable.Click to reveal answer
What does this code do?
my_dict['color'] = 'blue'✗ Incorrect
Assigning a value to a key adds it if missing or updates it if present.
Which method adds multiple key-value pairs to a dictionary at once?
✗ Incorrect
update() merges another dictionary or iterable of pairs into the dictionary.What does
setdefault('key', 0) do if 'key' is already in the dictionary?✗ Incorrect
setdefault returns the existing value if the key exists.If you want to change the value of an existing key, what should you do?
✗ Incorrect
Assigning a new value to the key updates it directly.
What will this code do?
my_dict.update({'x': 10, 'y': 20})✗ Incorrect
update() adds or updates multiple key-value pairs.Explain how to add a new key-value pair and update an existing key in a Python dictionary.
Think about using square brackets with the key.
You got /3 concepts.
Describe the difference between using assignment and the update() method to add or update dictionary entries.
One is for one pair, the other can handle many.
You got /3 concepts.