Dicts and Loops

dicts and loops

Dicts and loops

Video Transcript

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.
.keys() returns a list of the keys:
student = {"name": "Tom", "age": 17, "height": 68}

for key in student.keys():
  print(key)

# name
# age
# height
.values() returns a list of the values:
student = {"name": "Tom", "age": 17, "height": 68}

for value in student.values():
  print(value)

# Tom
# 17
# 68
.items() gets us the keys and the values at the same time, which we can acccess using two loop variables separated by a comma:
student = {"name": "Tom", "age": 17, "height": 68}

for key, value in student.items():
  print(f"{key}: {value}")

# name: Tom
# age: 17
# height: 68
Last section Next section