Looping Through Dictionaries
-
This lesson teaches how to iterate through dictionary keys and values in Python.
What Does “Looping Through Dictionary” Mean?
Looping through a dictionary means accessing each key and value one by one using a loop.
👉 Since a dictionary stores data in key : value format, Python allows us to loop in different ways.
Why We Use Looping in Dictionaries?
We use it to:
Display all data
Process each record
Search or filter data
Work with dynamic data like JSON, APIs, user input
Example Dictionary
student = {
"name": "Amit",
"age": 20,
"course": "Python"
}
1.Loop Through Keys Only
Syntax
for key in dictionary:
print(key)
Looping Keys
This loop prints only the keys of the dictionary.
student = {"name": "Amit", "age": 20, "course": "Python"}
for key in student:
print(key)
2.Loop Through Values Only
Syntax
for value in dictionary.values():
print(value)
Looping Values
This loop prints only the values stored in the dictionary.
student = {"name": "Amit", "age": 20, "course": "Python"}
for value in student.values():
print(value)
3.Loop Through Key–Value Pairs
Syntax
for key, value in dictionary.items():
print(key, value)
Looping Key-Value Pairs
This loop prints both keys and their corresponding values.
student = {"name": "Amit", "age": 20, "course": "Python"}
for key, value in student.items():
print(key, ":", value)
Loop With Condition
This example prints only values greater than 18.
marks = {"Amit": 85, "Riya": 90, "Rahul": 40}
for name, mark in marks.items():
if mark > 50:
print(name, "Passed")
Updating Dictionary Values
This example increases each student's marks by 5.
marks = {"Amit": 85, "Riya": 90}
for key in marks:
marks[key] += 5
print(marks)
Summary Table