Back to course

Dictionaries 3: Iterating Over Keys, Values, and Items

Python Programming: The 0 to Hero Bootcamp

Dictionary Iteration

Dictionaries offer three main ways to iterate, depending on whether you need the keys, the values, or both.

python scores = {'Math': 95, 'Science': 88, 'History': 76}

1. Iterating Over Keys (.keys())

Iterating directly over the dictionary (or using .keys()) iterates through the keys.

python for subject in scores.keys(): print(f"Subject: {subject}")

Also works:

for subject in scores:

print(f"Subject: {subject}")

2. Iterating Over Values (.values())

Iterates through the values only.

python for score in scores.values(): print(f"Score received: {score}")

3. Iterating Over Key-Value Pairs (.items())

This is the most common iteration method, as it allows access to both the key and the value simultaneously using tuple unpacking.

python for subject, score in scores.items(): print(f"The score for {subject} is {score}.")

Output:

The score for Math is 95. The score for Science is 88. The score for History is 76.