Free preview
100 lessons
Python Done Right
Free preview
Python Done Right · 100 lessons
No surprise gaps
Actually remember it
Skip what you know
One subscription. All learning paths included.
Our content is best on a larger screen
Updating a dictionary entry
To update an existing dictionary entry, we assign a new value to an existing key using the assignment operator =:
Syntax
dictionary[key] = new_value
For example:
# Simple dictionary representing player high scores
high_scores = {
'player1': 1500,
'player2': 3000,
'player3': 2200
}
# Updating the high score of player2
high_scores['player2'] = 3200
print(high_scores)
Output:
{'player1': 1500, 'player2': 3200, 'player3': 2200}
Practice questions
4 questions
The scores for a high-stakes gaming tournament where players earn points each round are stored in the following dictionary:
scores = {
"dragonSlayer": 500,
"DragonMaster": 750,
88: 1200
}
Which of the following options updates the scores for player "dragonSlayer" to 550 and for player 88 to 1300?
Select the correct answer:
+ 3 more questions
Adding a new entry to a dictionary
To add a new entry, we use the same syntax as updating - but with a key that doesn't yet exist:
Syntax
dictionary[key] = new_value
For example:
# Simple dictionary representing fruit prices
fruit_prices = {
'apple': 0.50,
'banana': 0.30,
'cherry': 1.25
}
# Adding the price of an orange
fruit_prices['orange'] = 0.8
# Checking the updated dictionary
print(fruit_prices)
Output:
{'apple': 0.5, 'banana': 0.3, 'cherry': 1.25, 'orange': 0.8}
Warning
Since the same syntax updates existing keys and creates new ones, we need to be careful not to unintentionally overwrite existing entries. We can use membership testing to check first.
Consider tracking player top scores - we only want to update if the new score is higher:
top_scores = {"player1": 1500, "player2": 1800, "player3": 1700}
new_player = "player1"
new_score = 2000
# Update or add new score if it's higher
if (
new_player not in top_scores
or new_score > top_scores[new_player]
):
top_scores[new_player] = new_score
print(f"{new_player}'s score updated to {new_score}.")
else:
print(
f"{new_player} already has a higher score of {top_scores[new_player]}."
)
print("Updated player top scores:", top_scores)
Output:
player1's score updated to 2000.
Updated player top scores: {'player1': 2000, 'player2': 1800, 'player3': 1700}
The condition checks if the player is new (not in top_scores) or has beaten their previous score - if either is true, we update their entry.
Practice questions
4 questions
In the Python Console there's a dictionary defined called singer_to_song. Add the following entries to it:
"Elton John" as the singer, "Rocket Man" as the song."Lady Gaga" as the singer, "Poker Face" as the song.Once done, assign the result to a variable named answer and press submit.
+ 3 more questions
Removing an entry from a dictionary
We can remove a dictionary entry using the del statement:
Syntax
del dictionary[key]
For example:
inventory = {'hammers': 10, 'screws': 50, 'nails': 100}
# Removing an entry with key 'screws'
del inventory['screws']
print(inventory) # Output: {'hammers': 10, 'nails': 100}
If the key is not found, attempting to delete it using del will raise a KeyError exception.
inventory = {'hammers': 10, 'screws': 50, 'nails': 100}
# Try removing an entry with key 'wrenches'
del inventory['wrenches'] # Will raise a KeyError
Practice questions
4 questions
In the Python Console, a dictionary employee_access is defined, where the keys represent employee IDs and the values represent their current access level to the system.
Some employees have left the company, and their access needs to be removed from the dictionary:
"emp123""emp456""emp789"Once you've updated the employee_access dictionary to remove these entries, assign the updated dictionary to a variable named answer and press submit.
+ 3 more questions
Dictionary keys
What can be a dictionary key?
There are a couple of constraints on what can be a dictionary key:
*tuples can only be used as dictionary keys if all elements within the tuple are themselves immutable.
Warning
Whilst keys must be unique, duplicate keys will not raise an error - the latter value simply overwrites the first:
my_dict = {"a": 1, "b": 2, "a": 3}
print(my_dict) # Output: {'a': 3, 'b': 2}
Practice questions
4 questions
Which of the following statements about dictionary keys is true?
Select the correct answer:
+ 3 more questions