Working with Keys and Values
In the last section, we briefly mentioned how to access a value stored in a dictionary and how to update these values. In this section, we're going to dive a little deeper into how you can work with dictionary keys and values, and check for membership in a dictionary.
Dictionaries and loops
Let's start by listing the contents of a dictionary. We can create a new dictionary of students, where the keys are the students' names, and the values are their attendance percentages for a given course:
student_attendance = {
"Rolf": 96,
"Bob": 80,
"Anne": 100
}
We can use the keys individually to get each attendance value, but when we're doing a repeated action like this, it's generally a good idea to use a loop. It makes our code shorter, easier to maintain, and easier to read.
Let's define a for loop to get each item in the dictionary:
for student in student_attendance:
print(student)
Unfortunately, this doesn't quite do what we want. The code above will just print the keys for the dictionary, not the values.
There are a couple of ways we can get the output we want. The first is that we can use the list of keys to grab the values from the student_attendance
dictionary like so:
for student in student_attendance:
print(f"{student}: {student_attendance[student]}")
The other option is to use the .items()
method. When iterating over the student_attendance
dictionary, we can iterate over student_attendance.items()
instead, which returns two items: the key, and the value. We can therefore provide two variables as part of our for loop to capture these values.
for student, attendance in student_attendance.items():
print(f"{student}: {attendance}")
Either option would print:
Rolf: 96
Bob: 80
Anne: 100
You can also iterate over a dictionaries values in a similar way using .values()
.
Checking for dictionary membership
We can easily check if a key exists in a particular dictionary using the in
keyword, much like we do with lists.
Using the attendance example above, we might check if we have an attendance score for Bob
like so:
if "Bob" in student_attendance:
print(f"Bob: {student_attendance[student]}")
else:
print("Bob isn't a student in this class!")