In this section, we're going to learn how to use loops with
dictionaries. To loop over a dictionary, we use the same
in
keyword as with a list. This will give us the keys in
the dictionary one at a time, which we can then use to access the
values:
student = {"name": "Tom", "age": 17, "height": 68}
for key in student:
print(f"{key}: {student[key]}")
# name: Tom
# age: 17
# height: 68
There are also a few built-in dictionary methods that give us
more flexibility over our loops.
student = {"name": "Tom", "age": 17, "height": 68}
for key in student.keys():
print(key)
# name
# age
# height
student = {"name": "Tom", "age": 17, "height": 68}
for value in student.values():
print(value)
# Tom
# 17
# 68
student = {"name": "Tom", "age": 17, "height": 68}
for key, value in student.items():
print(f"{key}: {value}")
# name: Tom
# age: 17
# height: 68