Python: Using Dictionaries Flashcards

1
Q

Once you have a dictionary, you can access the values in it by providing the __?__

A

key

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

what is the syntax to access the values of a dictionary?

A

dictionary[“key”]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

how would you check to determine if a key exists in a dictionary?
key = “Landmark 81”
dictionary = building_heights

A

key_to_check = “Landmark 81”

if key_to_check in building_heights:

print(building_heights[“Landmark 81”])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

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!”)

A
key_to_check = "Landmark 81"
try:
  print(building_heights[key_to_check])
except KeyError:
  print("That key doesn't exist!")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

what method can be used to search for a value in a dictionary besides my_dict[key] notation?

A

the .get() method

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

what syntax do we use to remove a key from a dictionary ?

A

.pop()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

__?__ works to delete items from a dictionary, when you know the key value.

A

.pop()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

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
A

health_points += available_items.pop(“stamina grains”, 0)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

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.

A

for student in test_scores.keys():

print(student)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Create a variable called users and assign it to be all of the keys of the user_ids list.

A

users = user_ids.keys()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

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.

A

total_exercises = 0

for exercises in num_exercises.values():
total_exercises += exercises

How well did you know this?
1
Not at all
2
3
4
5
Perfectly