Table of Contents
ToggleLooping through dictionaries in Python lets you access keys, values, or both to perform powerful operations. In this lesson, you’ll learn four key techniques—using a for loop directly, and the items(), keys(), and values() methods. Let’s dive in!
A for loop iterates over a dictionary’s keys by default. Use indexing to access values.
student = {"name": "Alice", "age": 21, "major": "Computer Science"}
for key in student:
print(key, student[key])
Output: name Alice, age 21, major Computer Science
The items() method returns a dynamic view of key-value pairs, perfect for looping over both at once.
student = {"name": "Alice", "age": 21, "major": "Computer Science"}
for key, value in student.items():
print(key, value)
Output: name Alice, age 21, major Computer Science
The keys() method gives a dynamic view of keys, letting you loop through them alone.
student = {"name": "Alice", "age": 21, "major": "Computer Science"}
for key in student.keys():
print(key)
Output: name, age, major
The values() method provides a dynamic view of values, ideal for looping through them directly.
student = {"name": "Alice", "age": 21, "major": "Computer Science"}
for value in student.values():
print(value)
Output: Alice, 21, Computer Science
Key Takeaway: Use for loops with items() for pairs, keys() for keys, or values() for values to unlock flexible dictionary iteration!
