0
0
PythonHow-ToBeginner · 3 min read

How to Iterate Over Dictionary Keys in Python Easily

To iterate over dictionary keys in Python, use a for loop directly on the dictionary or use the .keys() method. Both ways let you access each key one by one for processing.
📐

Syntax

You can loop over dictionary keys in two main ways:

  • for key in dictionary: loops over keys directly.
  • for key in dictionary.keys(): explicitly loops over keys.

Both give you each key in the dictionary one at a time.

python
for key in dictionary:
    # use key

# or

for key in dictionary.keys():
    # use key
💻

Example

This example shows how to print all keys from a dictionary using both methods.

python
my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}

print('Using for key in dictionary:')
for key in my_dict:
    print(key)

print('\nUsing for key in dictionary.keys():')
for key in my_dict.keys():
    print(key)
Output
Using for key in dictionary: apple banana cherry Using for key in dictionary.keys(): apple banana cherry
⚠️

Common Pitfalls

One common mistake is trying to loop over dictionary.values() when you want keys, which gives values instead. Another is modifying the dictionary while looping over it, which can cause errors.

Always loop over keys if you want keys, and avoid changing the dictionary during iteration.

python
my_dict = {'a': 1, 'b': 2}

# Wrong: looping over values when keys needed
for key in my_dict.values():
    print(key)  # prints values, not keys

# Correct: loop over keys
for key in my_dict:
    print(key)
Output
1 2 a b
📊

Quick Reference

Remember these tips for iterating dictionary keys:

  • Use for key in dictionary: for simple key iteration.
  • .keys() method is explicit but optional.
  • Do not modify the dictionary while looping.
  • Use dictionary.values() to get values, not keys.

Key Takeaways

Use a for loop directly on the dictionary to iterate over keys.
The .keys() method is optional but makes your intent clear.
Avoid modifying the dictionary while iterating over its keys.
Do not confuse keys with values; use .values() for values.
Iterating keys lets you access or manipulate dictionary entries easily.