|
| Home |
|---|
Iterating through dictionary keys means accessing each key stored inside a dictionary one by one.
Dictionaries store information as key-value pairs. Sometimes we need to work only with the keys of a dictionary, for example when displaying labels, searching specific keys, or processing dictionary data step-by-step.
Python provides multiple ways to loop through dictionary keys using loops and built-in dictionary methods.
The simplest way to iterate through dictionary keys
is by using a for loop.
When a dictionary is used directly in a loop, Python automatically returns its keys. This means we do not need to call any special method.
The loop will run once for every key stored in the dictionary.
for key in dictionary:
print(key)
student = {
"name":"Alice",
"age":21,
"course":"Python"
}
for key in student:
print(key)
name
age
course
The loop runs three times because the dictionary contains three keys: name, age and course.
Each iteration prints one key from the dictionary.
After retrieving each key, we can use it to access the corresponding value stored in the dictionary.
This is a very common pattern when displaying dictionary data.
student = {
"name":"Alice",
"age":21,
"course":"Python"
}
for key in student:
print(key, student[key])
name Alice
age 21
course Python
The loop retrieves each key and then accesses the value
using the expression student[key].
This prints both the key and the value together.
Python dictionaries provide a built-in method called
keys().
This method returns all dictionary keys. We can then iterate through those keys using a loop.
dictionary.keys()
student = {
"name":"Alice",
"age":21,
"course":"Python"
}
for key in student.keys():
print(key)
name
age
course
The keys() method returns all dictionary keys,
and the loop prints them one by one.
Although this produces the same result as the previous example, many programmers use this method because it clearly shows that we are working with dictionary keys.
Sometimes we may want to store the dictionary keys inside a list for further processing.
This can be useful when sorting keys or performing list operations.
student = {
"name":"Alice",
"age":21,
"course":"Python"
}
keys_list = list(student.keys())
print(keys_list)
['name', 'age', 'course']
The list() function converts the dictionary keys
into a Python list.
Once the keys are inside a list, we can perform operations such as sorting or indexing.
Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.
Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.
Home Tutorial Online Live Trainings Contact Us © 2026 All rights reserved by www.PythonTutor.net