Python: Using Dictionaries Flashcards
Once you have a dictionary, you can access the values in it by providing the __?__
key
what is the syntax to access the values of a dictionary?
dictionary[“key”]
how would you check to determine if a key exists in a dictionary?
key = “Landmark 81”
dictionary = building_heights
key_to_check = “Landmark 81”
if key_to_check in building_heights:
print(building_heights[“Landmark 81”])
update the line of code below to include the try/except method
key_to_check = “Landmark 81”
print(building_heights[key_to_check])
except KeyError:
print(“That key doesn’t exist!”)
key_to_check = "Landmark 81" try: print(building_heights[key_to_check]) except KeyError: print("That key doesn't exist!")
what method can be used to search for a value in a dictionary besides my_dict[key] notation?
the .get() method
what syntax do we use to remove a key from a dictionary ?
.pop()
__?__ works to delete items from a dictionary, when you know the key value.
.pop()
From the list below:
In one line, add the value of “stamina grains” to health_points and remove the item from the dictionary. If the key does not exist, add 0 to health_points.
available_items = {"health potion": 10, "cake of the cure": 5, "green elixir": 20, "strength sandwich": 25, "stamina grains": 15, "power stew": 30} health_points = 20
health_points += available_items.pop(“stamina grains”, 0)
Using the dictionary below.
test_scores = {“Grace”:[80, 72, 90], “Jeffrey”:[88, 68, 81], “Sylvia”:[80, 82, 84], “Pedro”:[98, 96, 95], “Martin”:[78, 80, 78], “Dina”:[64, 60, 75]}
write a code to print print out the list of keys in the dictionary.
for student in test_scores.keys():
print(student)
Create a variable called users and assign it to be all of the keys of the user_ids list.
users = user_ids.keys()
Create a variable called total_exercises and set it equal to 0.
Iterate through the values in the num_exercises list and add each value to the total_exercises variable.
total_exercises = 0
for exercises in num_exercises.values():
total_exercises += exercises