What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
Use for key in my_dict to loop over keys, my_dict.values() for values, and my_dict.items() to get each key and value together. A direct dictionary loop follows insertion order in Python 3.7 and later.
Choose the loop that returns what you need
Python dictionaries are iterable. Looping over a dictionary directly yields its keys, so you can use each key to look up its value when needed.
scores = {"Ada": 95, "Lin": 88}
for name in scores:
print(name, scores[name])
For other situations, use the dictionary’s values() or items() view:
| Loop form | What it yields | Use it when |
|---|---|---|
for key in d |
Keys | You need the keys, or will look up values with d[key]. |
for value in d.values() |
Values | You need values but not their keys. |
for key, value in d.items() |
Key-value pairs | You need both parts of each entry together. |
for key in sorted(d) |
Keys in sorted order | You need sorted traversal rather than insertion order. |
Loop over values only
Call values() when the key is irrelevant. Each iteration assigns the next value to the loop variable.
#1 Best Overall
for score in scores.values():
print(score)
Loop over keys and values together
Call items() to get each entry as a (key, value) pair. Python can unpack that pair directly into two loop variables.
for name, score in scores.items():
print(name, score)
What order does dictionary iteration use?
In Python 3.7 and later, dictionaries preserve insertion order as a language guarantee. In Python 3.6, insertion order was preserved by CPython as an implementation detail, not guaranteed by the language. The Python documentation describes dictionary behavior and ordering.
Rank #2
- Assigning a new value to an existing key does not move that key from its current position.
- Deleting a key and then adding it again places it at the end of the order.
How to iterate over keys in sorted order
Pass the dictionary to sorted() to loop over its keys in sorted order:
for key in sorted(scores):
print(key, scores[key])
sorted() returns a sorted list of keys; it does not rearrange the dictionary or change its insertion order.
Can you change a dictionary while iterating over it?
keys(), values(), and items() return dynamic views: they reflect changes to the underlying dictionary. Avoid adding or deleting entries while iterating over one of these views. Python’s documentation on dictionary view objects warns that changing the dictionary during iteration may raise a RuntimeError or cause the iteration to miss entries.
Quick Recap
Best Value
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

