Python · Dictionaries
Quizz
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Quiz: Valid Dictionary Syntax
Which of the following creates a valid dictionary?
Options
• ```codemon = {"name": "Aquachu", "level": 15}```
• ```codemon = ["name": "Aquachu", "level": 15]```
• ```codemon = {name: Aquachu, level: 15}```
• ```codemon = ("name": "Aquachu", "level": 15)```
Hint : Dictionaries use curly braces ```{}``` and keys must be strings in quotes.
Exercise 2 — Quiz: Create a Dictionary
Complete the code to create a dictionary with two key-value pairs.
stats ____ ____"hp"____ 100____ "attack"____ 75 ____
print(stats)
Options: = { : , } [ ] :
Hint : Remember: ```variable = {"key": value, "key2": value2}```
Exercise 3 — Quiz: Dictionary Values
What types of values can a dictionary contain?
Options
• Any data type (strings, numbers, lists, etc.)
• Only strings
• Only numbers
• Only strings and numbers
Hint : Think about what we've seen in dictionaries - can they hold lists, booleans, and other types?
Exercise 4 — Quiz: Dictionary Terminology
Match each term with its definition:
Items to match
• Key
• Value
• Key-Value Pair
• Empty Dictionary
Definitions
• The identifier used to access a value
• The data stored with a key
• One complete entry in a dictionary
• {}
Exercise 5 — Quiz: Duplicate Keys
What happens if you create a dictionary with duplicate keys?
codemon = {"type": "fire", "type": "water"}
print(codemon)
Options
• Only the last value is kept: ```{"type": "water"}```
• Both values are kept as a list
• An error is raised
• Only the first value is kept: ```{"type": "fire"}```
Hint : Dictionary keys must be unique - what happens when you redefine a key?
Exercise 6 — Quiz: Accessing Values
Complete the code to access the
"name"
value from the dictionary.
codemon = {"name": "Pyrochu", "level": 20}
name = codemon____________________
print(name)
Options: [ " name ] ( ) ' . "
Hint : Use square brackets with the key name in quotes.
Exercise 7 — Quiz: .get() vs [] Access
What's the advantage of using
.get()
instead of
[]
to access dictionary values?
Options
• ```.get()``` doesn't raise an error if the key doesn't exist
• ```.get()``` is faster
• ```.get()``` can modify values
• There is no difference
Hint : Think about what happens when you try to access a key that doesn't exist with each method.
Exercise 8 — Quiz: Updating Values
Complete the code to change the level to 25.
codemon = {"name": "Florachu", "level": 12}
codemon____"level"____ ____ 25
print(codemon)
Options: [ ] = : == . get
Hint : Use the same syntax as accessing, but with the assignment operator.
Exercise 9 — Quiz: Adding New Keys
How do you add a new key-value pair to an existing dictionary?
Options
• ```codemon["hp"] = 100```
• ```codemon.add("hp", 100)```
• ```codemon.insert("hp", 100)```
• ```codemon.append({"hp": 100})```
Hint : It's the same syntax as modifying - just use a key that doesn't exist yet!
Exercise 10 — Quiz: Checking Key Existence
What does
"level" in codemon
check?
Options
• If ```"level"``` exists as a key
• If ```"level"``` exists as a value
• If ```"level"``` is greater than 0
• If the dictionary is empty
Hint : The ```in``` operator checks keys by default, not values.
Exercise 11 — Quiz: Removal Methods
Match each removal method with what it does:
Items to match
• del dict[key]
• dict.pop(key)
• dict.popitem()
• dict.clear()
Definitions
• Remove a key without returning its value
• Remove a key and return its value
• Remove and return the last key-value pair
• Remove all items from the dictionary
Exercise 12 — Quiz: Using del
What happens if you use
del
on a key that doesn't exist?
Options
• A ```KeyError``` is raised
• Nothing happens
• ```None``` is returned
• The dictionary is cleared
Hint : ```del``` is not safe - it will complain if the key doesn't exist!
Exercise 13 — Quiz: Safe Removal with pop()
Complete the code to safely remove
"trainer"
with a default value of
"Unknown"
.
codemon = {"name": "Aquachu", "level": 10}
trainer = codemon.____("____","____")
print(trainer)
Options: pop " trainer , Unknown get remove '
Hint : Syntax: ```.pop(key, default_value)```
Exercise 14 — Quiz: popitem() Behavior
What does
.popitem()
return?
Options
• A tuple containing ```(key, value)```
• Just the key
• Just the value
• A list of all remaining keys
Hint : ```.popitem()``` removes and returns the last added pair as a tuple.
Exercise 15 — Quiz: After clear()
What does a dictionary look like after calling
.clear()
?
Options
• ```{}```
• ```None```
• ```[]```
• The dictionary is deleted
Hint : ```.clear()``` removes all items but keeps the dictionary itself.
Exercise 16 — Quiz: Get All Keys
Complete the code to get all dictionary keys.
codemon = {"name": "Pyrochu", "type": "fire", "level": 18}
all_keys = codemon.____()
print(all_keys)
Options: keys values items get pop clear
Hint : There's a method specifically for getting all keys!
Exercise 17 — Quiz: Checking Values
How do you check if a value exists in a dictionary?
Options
• ```"water" in codemon.values()```
• ```"water" in codemon```
• ```"water" in codemon.keys()```
• ```codemon.has_value("water")```
Hint : By default, ```in``` checks keys. To check values, use ```.values()```.
Exercise 18 — Quiz: What .items() Returns
What format does
.items()
return key-value pairs in?
Options
• Tuples: ```(key, value)```
• Lists: ```[key, value]```
• Dictionaries: ```{key: value}```
• Strings: ```"key: value"```
Hint : ```.items()``` returns pairs as tuples that can be unpacked.
Exercise 19 — Quiz: Method Purposes
Match each method with what it returns:
Items to match
• .keys()
• .values()
• .items()
• .get(key)
Definitions
• All the keys
• All the values
• All key-value pairs as tuples
• A single value (or None)
Exercise 20 — Quiz: Default 'in' Behavior
By default, what does the
in
operator check in a dictionary?
Options
• Keys only
• Values only
• Both keys and values
• The dictionary size
Hint : ```"name" in dict``` checks if ```"name"``` is a key.
Exercise 21 — Quiz: Basic Dictionary Loop
Complete the code to loop through dictionary keys by default.
stats = {"hp": 100, "attack": 75, "defense": 60}
____ stat ____ stats:
print(stat)
Options: for in while if from with
Hint : Use a standard for loop - Python will iterate over keys by default!
Exercise 22 — Quiz: Iterating Over Values
Which loop iterates over dictionary values only?
Options
• ```for value in dict.values():```
• ```for value in dict:```
• ```for value in dict.keys():```
• ```for value in dict.items():```
Hint : To get only values, you need to explicitly use ```.values()```.
Exercise 23 — Quiz: Unpacking Key-Value Pairs
Complete the code to loop through both keys and values.
codemon = {"name": "Aquachu", "level": 15}
for ____________ in codemon.____():
print(f"{key}: {value}")
Options: key , value items values keys pairs
Hint : Use ```.items()``` and unpack into two variables!
Exercise 24 — Quiz: Summing Values
What's the best way to calculate the sum of all dictionary values?
Options
• Loop through ```.values()``` and add each one
• Loop through ```.keys()``` and add each one
• Loop through ```.items()``` and add keys
Hint : You only need the values to sum them, not the keys!
Exercise 25 — Quiz: When to Use Each Method
Match each scenario with the best iteration method:
Items to match
• Calculate total of all numbers
• Check if certain keys exist
• Display formatted key: value pairs
• Filter items based on conditions
Definitions
• .values()
• .keys() or in
• .items()
• .items() with if
Back to the course