2. Dictionary with functions
2.1. Dictionaries
key: value pairs.2.2. Dictionary structure
car_dictionary = {"brand": "Ford", "model": "Mustang", "year": 1965}
2.3. Quiz: Dictionary Structure
2.3.1. Fill-in-the-Blanks (Cloze)
1. A dictionary is a collection of key-value Drop here.
2. A dictionary is created using curly Drop here.
3. Each key is separated from its value by a Drop here.
4. Each key-value pair is separated from the next pair by a Drop here.
5. Every key in a dictionary must be Drop here.
2.3.2. Code Ordering Examples
Example 1: Create a car dictionary and print it.
Example 2: Create a dictionary of pet ages, add a new pet, and print the dictionary.
2.3.3. Multiple Choice Questions
How many keys are in car_dictionary = {"brand": "Ford", "model": "Mustang", "year": 1965}?
Incorrect. Each key-value pair has its own key.
Incorrect. Count each pair separated by commas.
Correct! The keys are “brand”, “model” and “year”.
Incorrect. len() counts pairs, not keys and values separately.
Which of the following CANNOT be used as a dictionary key?
Incorrect. Strings are the most common type of key.
Incorrect. Integers can be keys.
Incorrect. Tuples can be keys because they cannot be changed.
Correct! Lists can be changed, so they cannot be used as keys.
What is the value paired with the key "model" in car_dictionary?
Incorrect. “Ford” is the value for “brand”.
Correct! “model”: “Mustang” is the second key-value pair.
Incorrect. 1965 is the value for “year”.
Incorrect. “model” is the key, not the value.
What is stored in d after running d = {"a": 1, "a": 2}?
Incorrect. Duplicate keys are not possible.
Incorrect. The later value overwrites the earlier one.
Correct! The second “a” overwrites the first.
Incorrect. Python allows this but keeps only the last value.
Which line is a correctly written dictionary?
Correct! Curly braces, colons between keys and values, commas between pairs.
Incorrect. Keys and values are separated by colons, not equals signs.
Incorrect. Square brackets create lists.
Incorrect. A comma is missing between the pairs.
2.4. Looking up dictionary values by key
- value = dictionary[key]
- Get the value of a specific key in a dictionary.Raises an error if the key doesn’t exist, so a try-except block is needed.
Example:
car_dictionary = {"brand": "Ford", "model": "Mustang", "year": 1965}
# key exists
value = car_dictionary["brand"]
print(value)
# key doesn't exist
try:
value = car_dictionary["brands"]
print(value)
except KeyError:
print("not a valid key")
2.5. Looking up dictionary values by the get method
- dict.get(key, default=None)
Returns the value for the specified key if the key is in the dictionary, otherwise returns the default value.
Example:
car_dictionary = {"brand": "Ford", "model": "Mustang", "year": 1965}
# without default
value = car_dictionary.get("brand")
print(value)
# output is "Ford"
# without default; returns None
value = car_dictionary.get("brands")
print(value)
# output is None
# with default
value = car_dictionary.get("brands", "not a valid key")
print(value)
# output is "not a valid key"
2.6. Check if the key is in the dictionary
- key in dictionary
- Returns True if the key is among the keys of the dictionary; False if not.
Example:
car_dictionary = {"brand": "Ford", "model": "Mustang", "year": 1965}
# key exists
key_exists = "model" in car_dictionary
print(key_exists)
# key doesn't exists
key_exists = "models" in car_dictionary
print(key_exists)
2.7. Quiz: Looking Up Values
2.7.1. Fill-in-the-Blanks (Cloze)
1. Looking up a missing key with square brackets raises a Drop here.
2. To handle a missing key without the program crashing, wrap the lookup in a Drop here-except block.
3. The Drop here method returns a default value instead of raising an error when a key is missing.
4. If no default is given, ``.get()`` returns Drop here for a missing key.
5. The Drop here keyword returns True if a key is in the dictionary and False if it is not.
2.7.2. Code Ordering Examples
Example 1: Look up a key that might not exist, using a try-except block.
Example 2: Look up a key with .get() and a default value, then print the result.
Example 3: Check whether a key exists before printing its value.
2.7.3. Multiple Choice Questions
What does car_dictionary["year"] return?
Correct! The value stored with the key “year” is 1965.
Incorrect. Square brackets return the value, not the key.
Incorrect. “Mustang” is the value for “model”.
Incorrect. The key exists, so its value is returned.
What happens when you run car_dictionary["Brand"]?
Incorrect. Keys are case-sensitive, so “Brand” is not the same as “brand”.
Correct! “Brand” with a capital B is not a key in the dictionary.
Incorrect. Square brackets raise an error rather than returning None.
Incorrect. Looking up a key never adds it.
Which exception should the except line catch when looking up a missing key with square brackets?
Incorrect. IndexError is for list positions that are out of range.
Incorrect. ValueError is for values of the wrong kind, such as int(“abc”).
Correct! A missing dictionary key raises a KeyError.
Incorrect. NameError is for variables that have not been defined.
What does car_dictionary.get("colour") return?
Incorrect. .get() returns a value, not the key.
Incorrect. The default return value is None.
Correct! With no default given, .get() returns None for a missing key.
Incorrect. .get() never raises a KeyError.
What does car_dictionary.get("colour", "unknown") return?
Correct! “colour” is missing, so the default value is returned.
Incorrect. A default value was given, so it is returned instead of None.
Incorrect. .get() returns the default, not the key.
Incorrect. .get() never raises a KeyError.
What does car_dictionary.get("brand", "unknown") return?
Correct! The key exists, so its real value is returned and the default is ignored.
Incorrect. The default is only used when the key is missing.
Incorrect. .get() returns the value, not the key.
Incorrect. The key exists.
What does "Ford" in car_dictionary evaluate to?
Incorrect. The in keyword checks keys, and “Ford” is a value.
Correct! “Ford” is a value, not a key.
Incorrect. The in keyword returns True or False.
Incorrect. The in keyword never raises a KeyError.
What does "year" in car_dictionary evaluate to?
Correct! “year” is one of the keys.
Incorrect. “year” is a key in the dictionary.
Incorrect. The in keyword returns True or False, not the value.
Incorrect. The in keyword returns True or False.
Why might you choose .get() instead of square brackets?
Correct! .get() returns None or a default instead of crashing.
Incorrect. Square brackets also read values.
Incorrect. .get() never changes the dictionary.
Incorrect. .keys() returns all the keys.
Which code safely prints “missing” when the key "colour" is not in car_dictionary?
Incorrect. Square brackets do not take a default value.
Correct! The second argument to .get() is the default.
Incorrect. Dictionaries do not have a .find() method.
Incorrect. This prints False missing.
2.8. Definition to get a dictionary value
2.8.1. Create a dictionary
Tasks
Create a dictionary, rainbow_colors, with the colour name as the key and the hex value as the value.
Create a dictionary, rainbow_colors, with the colour name as the key and the hex value as the value.
# Dictionary for rainbow colors
rainbow_colors = {
"red": "#FF0000",
"orange": "#FFA500",
"yellow": "#FFFF00",
"green": "#008000",
"blue": "#0000FF",
"indigo": "#4B0082",
"violet": "#EE82EE"
}
2.8.2. User input
- input(prompt)
- prompt is a string, representing a default message for the input.Returns a string.
Example:
colour = input("Enter a colour: ")
print(colour)
Tasks
Create a user input that refers to all the possible colors and stores it in the variable, user_color.
Create a user input that refers to all the possible colors and stores it in the variable, user_color
user_color = input("Enter a color from the rainbow (red, orange, yellow, green, blue, indigo, violet): ")
2.8.3. Hex colour function
A scaffold of a simple function to return the hex value of a colour is below.
def hex_color(user_color, ________________):
# Convert the input to lowercase for case-insensitivity
user_color = ______________.lower()
return ________________.get(_________________, "not listed in the dictionary")
1. The second parameter of the function is Drop here.
2. The ``.lower()`` method is called on Drop here.
3. The ``.get()`` method is called on Drop here.
4. The first argument passed to ``.get()`` is Drop here.
Check: Put the lines of the completed function in the correct order.
2.8.4. Final code
Exercise
Create a python script that gets user input and prints the hex colour for the color name the user inputs.
Example output: The hexadecimal value for green is #008000.
Create a python script that gets user input and prints the hex colour for the color name the user inputs.
Example output: The hexadecimal value for green is #008000.
# Dictionary with rainbow colors
rainbow_colors = {
"red": "#FF0000",
"orange": "#FFA500",
"yellow": "#FFFF00",
"green": "#008000",
"blue": "#0000FF",
"indigo": "#4B0082",
"violet": "#EE82EE"
}
user_color = input('Enter a rainbow color (red, orange, yellow, green, blue, indigo, violet): ')
def hex_color(user_color, rainbow_colors):
# Convert the input to lowercase for case-insensitivity
user_color = user_color.lower()
return rainbow_colors.get(user_color, "not listed in the dictionary")
hex_val = hex_color(user_color, rainbow_colors)
print(f"The hexadecimal value for {user_color} is {hex_val}")
2.9. Quiz: Rainbow Hex Colours
2.9.1. Fill-in-the-Blanks (Cloze)
1. The ``input()`` function always returns a Drop here.
2. Calling ``.lower()`` on the input makes the lookup case-Drop here.
3. The ``hex_color`` function takes the colour name and the Drop here as its parameters.
4. When the colour is not a key, ``.get()`` returns its Drop here value.
5. A function sends its result back to the code that called it using the Drop here keyword.
2.9.2. Code Ordering Examples
Example 1: Ask for a colour, call the function, and print the result.
Example 2: Create a small colour dictionary, look up “blue” with the function, and print the result.
2.9.3. Multiple Choice Questions
What data type does input() return?
Correct! input() always returns a string, even if the user types a number.
Incorrect. You would need int() to convert the input to an integer.
Incorrect. input() returns the text the user typed.
Incorrect. input() returns the text the user typed.
Why does hex_color call .lower() on user_color?
Correct! The dictionary keys are lowercase, and keys are case-sensitive.
Incorrect. .strip() removes spaces.
Incorrect. .lower() changes letters to lowercase.
Incorrect. .get() works with any key; the keys here happen to be lowercase.
What does hex_color("GREEN", rainbow_colors) return?
Correct! “GREEN” is converted to “green”, which is a key.
Incorrect. .lower() converts “GREEN” to “green” before the lookup.
Incorrect. The key is found after converting to lowercase.
Incorrect. .get() never raises a KeyError.
What does hex_color("purple", rainbow_colors) return?
Incorrect. Purple is not in the rainbow_colors dictionary.
Incorrect. A default value was passed to .get().
Correct! “purple” is missing, so the default value is returned.
Incorrect. .get() never raises a KeyError.
Why does the function use .get() instead of rainbow_colors[user_color]?
Correct! Square brackets would raise a KeyError.
Incorrect. Square brackets work anywhere.
Incorrect. The reason is handling missing keys safely.
Incorrect. .get() never changes the dictionary.
What does "#FF0000" in rainbow_colors evaluate to?
Incorrect. The in keyword checks keys, and “#FF0000” is a value.
Correct! “#FF0000” is a value, not a key.
Incorrect. The in keyword returns True or False.
Incorrect. The in keyword never raises a KeyError.
In hex_val = hex_color(user_color, rainbow_colors), what is stored in hex_val?
Correct! The returned hex value (or default message) is stored in hex_val.
Incorrect. That is stored in user_color.
Incorrect. The dictionary is passed in, not returned.
Incorrect. The function always returns a string.
What would happen if the return line were removed from hex_color?
Incorrect. Nothing in the function prints.
Correct! A function with no return statement returns None.
Incorrect. No lookup would raise an error.
Incorrect. Without return, the result is None.