Computer Science
Grade 8
20 min
Adding and Removing Items from Dictionaries
Learn how to add and remove key-value pairs from dictionaries. Practice manipulating dictionaries.
Tutorial Preview
1
Introduction & Learning Objectives
Learning Objectives
Define what a dictionary is and its key-value pair structure.
Explain the purpose of adding new items to a dictionary.
Demonstrate how to add a new key-value pair to an existing dictionary.
Explain the purpose of removing items from a dictionary.
Demonstrate how to remove a key-value pair from a dictionary using its key.
Differentiate between adding a new item and updating an existing item in a dictionary.
Identify scenarios where dynamically adding or removing dictionary items is useful.
Ever wondered how your favorite online store keeps track of all the items in your shopping cart? 🛒 Or how a game remembers your character's inventory? 🤔
In this lesson, you'll learn about dictionaries, a powerful way to organize information using key-value...
2
Key Concepts & Vocabulary
TermDefinitionExample
DictionaryA collection of key-value pairs, where each unique key is used to look up its associated value. Think of it like a real-world dictionary where words (keys) have definitions (values).A dictionary for a student's grades: `{"Math": 90, "Science": 85}`
Key-Value PairThe fundamental unit of a dictionary, consisting of a unique 'key' that acts as an identifier, and its associated 'value' which is the data stored.In `{"item": "apple"}`, 'item' is the key and 'apple' is the value.
Adding an ItemThe process of inserting a new key-value pair into a dictionary. If the key already exists, this operation will instead update its value.`my_dict["new_key"] = "new_value"...
3
Core Syntax & Patterns
Adding or Updating Dictionary Items
dictionary_name[key] = value
To add a new item, use square brackets with a new key and assign a value. If the key already exists, this syntax will update the value associated with that key instead of adding a new item.
Removing Dictionary Items with `del`
del dictionary_name[key]
The `del` keyword is used to permanently remove a key-value pair from a dictionary. You must provide the exact key of the item you want to remove. If the key does not exist, a `KeyError` will occur.
Removing Dictionary Items with `pop()`
removed_value = dictionary_name.pop(key, default_value_if_not_found)
The `pop()` method removes the specified key-value pair and returns the value that was removed. If the key is not found and no `default_value_if_not_foun...
5 more steps in this tutorial
Sign up free to access the complete tutorial with worked examples and practice.
Sign Up Free to ContinueSample Practice Questions
Challenging
A shopping cart is represented by a dictionary `cart = {'apple': 2, 'milk': 1}`. A user wants to add one more apple. The code used is `cart['apple'] = cart['apple'] + 1`. Why does this single line of code work for updating an existing item but would fail if the item was new?
A.The code would actually work for a new item, creating it with a value of 1.
B.The right side, `cart['apple']`, would cause a `KeyError` if 'apple' was not already a key.
C.The `+ 1` operation is only allowed on existing key-value pairs.
D.The left side, `cart['apple'] = ...`, is what would cause an error for a new item.
Challenging
You are managing a dictionary of `active_users = {'user1': 'Alice', 'user2': 'Bob'}`. When a user logs out, you need to remove them from `active_users` and add their user ID to a `logout_log` list. Which code snippet correctly handles logging out 'user2'?
A.logout_log.append('user2'); del active_users['user2'];
B.logout_log = [active_users.pop('user2')]
C.del active_users['user2']; logout_log.append('user2');
D.logout_log.append(active_users.pop('user2'))
Challenging
What is the final state of the `scores` dictionary and the final value of the `status` variable after this code runs? `scores = {'player1': 100}; status = scores.pop('player2', 'Not Found'); scores['player2'] = 50;`
A.scores: `{'player1': 100, 'player2': 50}`, status: `50`
B.scores: `{'player1': 100}`, status: `'Not Found'`
C.scores: `{'player1': 100, 'player2': 50}`, status: `'Not Found'`
D.The code will crash with a `KeyError`.
Want to practice and check your answers?
Sign up to access all questions with instant feedback, explanations, and progress tracking.
Start Practicing Free