22. Python Dictionary Methods
.keys(), .values(), .items(), .get(), and .pop().student = {
"name": "Alex",
"age": 13,
"grade": "Year 8"
}
# Accessing values safely using .get()
print(student.get("name")) # Output: Alex
22.1. Accessing Keys, Values, and Items
Python provides built-in methods to extract different parts of a dictionary as dynamic view objects:
The .keys() Method: Returns a view object containing all the keys present in the dictionary.
The .values() Method: Returns a view object containing all the values stored in the dictionary.
The .items() Method: Returns a view object containing key-value pairs as tuples
(key, value).Iterating and Inspection: These methods make it easy to loop through keys, values, or both simultaneously.
scores = {"Alice": 95, "Bob": 88, "Charlie": 92}
print(scores.keys()) # Output: dict_keys(['Alice', 'Bob', 'Charlie'])
print(scores.values()) # Output: dict_values([95, 88, 92])
print(scores.items()) # Output: dict_items([('Alice', 95), ('Bob', 88), ('Charlie', 92)])
22.1.1. Quiz: Accessing Keys, Values, and Items
22.1.1.1. Fill-in-the-Blanks (Cloze)
1. The Drop here method returns a view of all keys in a dictionary.
2. To get all values stored in a dictionary, use the Drop here method.
3. The `.items()` method returns key-value pairs grouped as Drop here.
4. Dictionaries store data in Drop here pairs.
5. View objects returned by `.keys()` automatically Drop here when the dictionary changes.
22.1.1.2. Code Ordering Examples
Example 1: Extract and display all keys from a inventory dictionary.
Example 2: Loop through all values stored in a game score dictionary.
Example 3: Print key and value pairs together using the .items() method.
22.1.1.3. Multiple Choice Questions
Which method returns all the keys present in a Python dictionary?
Correct! The .keys() method extracts a view of all dictionary keys.
Incorrect. There is no .all_keys() method in Python.
Incorrect. Python uses .keys() directly.
Incorrect. Dictionaries are indexed by keys, not numerical indices.
What does the .values() method return?
Correct! .values() extracts every value in the dictionary.
Incorrect. .keys() retrieves key names.
Incorrect. len() determines key count.
Incorrect. .values() returns all stored values.
Given d = {"a": 1, "b": 2}, what is returned by d.items()?
Correct! .items() returns key-value pairs formatted as tuples.
Incorrect. That is returned by .keys().
Incorrect. That is returned by .values().
Incorrect. .items() returns a view object of tuples.
How do you loop through both keys and values simultaneously in a dictionary data?
Correct! .items() provides key and value in each iteration loop.
Incorrect. .keys() only yields key names.
Incorrect. .values() only yields dictionary values.
Incorrect. Iterating directly over a dictionary yields keys only.
What type of data structure are individual key-value pairs wrapped in inside .items()?
Correct! Key-value pairs are returned as immutable (key, value) tuples.
Incorrect. Items view uses tuples (key, value).
Incorrect. Original data types are preserved inside tuples.
Incorrect. Items view uses paired tuples.
Given fruit = {"apple": "red", "banana": "yellow"}, what does "apple" in fruit.keys() evaluate to?
Correct! “apple” is a key present in the dictionary.
Incorrect. “apple” is actively present as a key.
Incorrect. Membership test returns Boolean True or False.
Incorrect. Membership testing on key views is valid syntax.
If you modify a dictionary after calling k = dict.keys(), what happens to k?
Correct! Dictionary views reflect dictionary modifications dynamically.
Incorrect. Dictionary views are dynamic.
Incorrect. Dynamic view tracking is intentional behavior.
Incorrect. Object type remains a dictionary view.
Which method would you use to get a collection of ONLY player scores from {"p1": 50, "p2": 90}?
Correct! .values() returns all score numbers without player key names.
Incorrect. .keys() returns player names (“p1”, “p2”).
Incorrect. .pop() removes and returns a specific item.
Incorrect. .get() retrieves a single specified key’s value.
Given info = {"age": 14}, what is printed by print(type(info.keys()))?
Correct! .keys() returns a specialized dict_keys object.
Incorrect. Views can be converted to lists using list(), but are dict_keys types by default.
Incorrect. dict_keys is its own view type.
Incorrect. Key views are specialized iterable objects.
How can you convert dict.values() into a standard Python list?
Correct! The built-in list() function converts view objects into standard lists.
Incorrect. Method .to_list() does not exist in standard Python.
Incorrect. str() converts the object to a string representation.
Incorrect. This converts keys to a tuple instead of values to a list.
22.2. Safe Retrieval using .get()
Accessing a non-existent key using bracket notation (dict[key]) raises a KeyError. The ``.get()`` method provides a safe alternative:
Key Lookup: Returns the value associated with a specified key if it exists.
Default Fallback: Returns
None(or a custom specified default) if the key is missing instead of crashing the program.Custom Default Syntax: Pass a second argument to specify custom output when missing:
dict.get(key, default_value).Error Prevention: Prevents unexpected crashes when handling unpredictable data inputs.
profile = {"username": "Alex", "level": 5}
# Safe lookup for an existing key
print(profile.get("username")) # Output: Alex
# Safe lookup for a missing key with default fallback
print(profile.get("coins", 0)) # Output: 0 (since "coins" is not in profile)
22.2.1. Quiz: Safe Retrieval using .get()
22.2.1.1. Fill-in-the-Blanks (Cloze)
1. The `.get()` method prevents a program from raising a Drop here when a key is missing.
2. If a key is not found and no default is set, `.get()` returns Drop here.
3. To provide a custom fallback value, pass it as the Drop here argument to `.get()`.
4. Accessing `d["missing"]` directly causes Python to Drop here if the key doesn't exist.
5. In `dict.get("score", 0)`, the number `0` acts as the Drop here value.
22.2.1.2. Code Ordering Examples
Example 1: Safely fetch a user rank using .get() with a default value.
Example 2: Compare standard bracket notation with safe .get() retrieval.
Example 3: Check inventory count for an item not in stock.
22.2.1.3. Multiple Choice Questions
What happens when you request a missing key using standard square brackets (e.g., d["missing"])?
Correct! Missing keys in bracket notation crash with a KeyError.
Incorrect. .get() returns None, square brackets raise KeyError.
Incorrect. Standard lookups do not mutate dictionaries.
Incorrect. An exception is raised.
What is returned by {"a": 1}.get("b")?
Correct! When a key is missing and no default is given, .get() returns None.
Incorrect. .get() avoids raising KeyErrors.
Incorrect. 0 is only returned if explicitly passed as default.
Incorrect. Default fallback is None.
What is the output of {"hero": "Knight"}.get("shield", "No Shield")?
Correct! “shield” key is missing, so custom default “No Shield” is returned.
Incorrect. “Knight” is the value for “hero”, not “shield”.
Incorrect. Custom default overrides None.
Incorrect. .get() handles missing keys safely.
Given colors = {"red": "#FF0000"}, what does colors.get("red", "#000000") return?
Correct! Key “red” exists, so stored value “#FF0000” is returned instead of default.
Incorrect. Fallback value is ignored when key is found.
Incorrect. Stored value is returned.
Incorrect. Valid existing key lookup.
Which statement about .get() is TRUE?
Correct! .get() handles missing keys gracefully.
Incorrect. .get() does not modify dictionary content.
Incorrect. .get() reads values without removing keys.
Incorrect. Works with string, tuple, or integer keys.
What is the default return value of dict.get(key) if key is missing and no second parameter is provided?
Correct! None is Python’s built-in default for absent values in .get().
Incorrect. Must pass 0 explicitly as second parameter.
Incorrect. None is returned.
Incorrect. None is returned.
Given settings = {"volume": 80}, what is printed by print(settings.get("brightness", 50))?
Correct! Key “brightness” is absent, so fallback integer 50 prints.
Incorrect. 80 belongs to “volume”.
Incorrect. Custom fallback 50 overrides None.
Incorrect. Method handles missing key.
Why is .get() preferred over bracket lookup when reading user input keys?
Correct! Protects scripts from bad/unexpected key inputs.
Incorrect. Lookup speeds are virtually identical.
Incorrect. Square brackets read string keys fine.
Incorrect. Key casing is unchanged.
What is output by d = {}; print(d.get("x") is None)?
Correct! d.get(“x”) returns None, and None is None evaluates to True.
Incorrect. Lookup returns None.
Incorrect. No error raised.
Incorrect. Expression is valid syntax.
Does dict.get("key", "default") modify dict if "key" is not in dict?
Correct! .get() is strictly a non-mutating read operation.
Incorrect. Use .setdefault() if key addition is desired.
Incorrect. .get() never alters dictionary contents.
Incorrect. Non-mutating operation.
22.3. Modifying Dictionaries (.update, .pop, .clear)
To modify, remove, or update dictionary content, Python provides several key methods:
The .update() Method: Merges key-value pairs from another dictionary or iterable. Existing keys are overwritten, and new keys are added.
The .pop() Method: Removes a specified key and returns its value. Accepts a default parameter to prevent errors if key is missing.
The .popitem() Method: Removes and returns the last inserted key-value pair as a tuple
(key, value).The .clear() Method: Removes all key-value pairs from the dictionary, leaving it empty (
{}).
player = {"name": "Sam", "health": 100}
# Updating existing key and adding a new key simultaneously
player.update({"health": 90, "shield": 50})
print(player) # Output: {'name': 'Sam', 'health': 90, 'shield': 50}
# Removing a key and capturing its value using .pop()
removed_health = player.pop("health")
print(removed_health) # Output: 90
# Clearing all keys
player.clear()
print(player) # Output: {}
22.3.1. Quiz: Modifying Dictionaries
22.3.1.1. Fill-in-the-Blanks (Cloze)
1. The Drop here method merges another dictionary into an existing one.
2. To remove a key and return its value, use the Drop here method.
3. The `.popitem()` method removes the Drop here inserted key-value pair.
4. To remove all items from a dictionary at once, call the Drop here method.
5. Calling `.clear()` leaves a dictionary in an Drop here state `{}`.
22.3.1.2. Code Ordering Examples
Example 1: Update player score and add a new item using .update().
Example 2: Safely pop a key from a dictionary with a fallback value.
Example 3: Empty a configuration dictionary using .clear().
22.3.1.3. Multiple Choice Questions
What does the .update() method do when passed a key that ALREADY exists in the target dictionary?
Correct! .update() replaces existing key values with incoming data.
Incorrect. Overwriting existing keys is expected behavior.
Incorrect. Existing values are overwritten.
Incorrect. Python dictionaries cannot contain duplicate keys.
Given d = {"a": 10, "b": 20}, what does d.pop("a") return?
Correct! .pop() removes key “a” and returns its associated value 10.
Incorrect. .pop() returns the value, not the key name.
Incorrect. .pop() returns the removed value, not the modified dictionary.
Incorrect. Returns 10.
What happens if you run dict.pop("missing") on a dictionary that does NOT contain “missing”?
Correct! Like bracket lookup, .pop() without a default raises KeyError if key is absent.
Incorrect. .pop() requires a default value parameter to avoid KeyError on missing keys.
Incorrect. Dict content remains unless KeyError interrupts execution.
Incorrect. Must provide default parameter (e.g. .pop(“missing”, None)).
Which method removes ALL items from a dictionary, leaving it with length 0?
Correct! .clear() removes all key-value entries.
Incorrect. Python uses del statement or .clear() method.
Incorrect. .remove() is a list method, not a dictionary method.
Incorrect. No .reset() method exists for dictionaries.
What does .popitem() remove and return in Python 3.7+?
Correct! In Python 3.7+, dictionaries preserve insertion order, so .popitem() removes LIFO (last-in, first-out) item.
Incorrect. Dictionaries preserve insertion order in modern Python.
Incorrect. Removes the last pair added.
Incorrect. Removes a single pair.
Given data = {"x": 1}, what is the value of data after executing data.update({"y": 2})?
Correct! “y”: 2 is added as a new key-value pair.
Incorrect. .update() merges data without erasing existing keys.
Incorrect. New pair is inserted.
Incorrect. Valid dictionary update.
How can you prevent a KeyError when popping a potentially missing key “status” from info?
Correct! Providing a second default argument avoids KeyErrors if key is missing.
Incorrect. Raises KeyError if missing.
Incorrect. .clear() takes no arguments and empties dictionary.
Incorrect. .update() expects dictionary/iterable arguments.
Given items = {"a": 1, "b": 2}, what is len(items) after items.clear()?
Correct! .clear() empties dictionary, reducing length to 0.
Incorrect. All items are removed.
Incorrect. All items are removed.
Incorrect. len() returns integer 0.
Given d = {"a": 5}, what does d.pop("a") leave inside d?
Correct! Key “a” is removed, leaving an empty dictionary.
Incorrect. Key is removed by .pop().
Incorrect. Key and value are deleted.
Incorrect. d remains an empty dictionary object.
Which dictionary method accepts another dictionary as an argument to combine entries?
Correct! .update() takes another dictionary or key-value iterable as argument.
Incorrect. Takes key name and optional default.
Incorrect. Takes key name and optional default.
Incorrect. Takes no arguments.