Loop Through a Dictionary
Lesson 9 of 14 in Coddy's Dictionary in Python course.
Looping through a dictionary in Python allows you to iterate over its keys, values, or key-value pairs (items) to perform various operations. There are several ways to loop through a dictionary, depending on what you want to achieve:
Loop Through Keys:
You can use a for loop to iterate through the keys of a dictionary. Here's how you do it:
my_dict = {"a": 1, "b": 2, "c": 3}
for key in my_dict:
print(key)This code will print the keys "a," "b," and "c."
Loop Through Values:
If you want to loop through the values of a dictionary, you can use the .values() method
my_dict = {"a": 1, "b": 2, "c": 3}
for value in my_dict.values():
print(value)
This code will print the values 1, 2, and 3.
Loop Through Key-Value Pairs (Items):
To iterate through both the keys and values of a dictionary, you can use the .items() method:
my_dict = {"a": 1, "b": 2, "c": 3}
for key, value in my_dict.items():
print(key, value)
This code will print key-value pairs, like "a 1," "b 2," and "c 3."
You can use the
keys()method to return the keys of a dictionary.
Challenge
EasyCreate a function named calculate_average_grade that calculates the average grade of students in a class using a dictionary containing student names as keys and their corresponding grades as values. The function should loop through the dictionary and return the average grade.
Try it yourself
def calculate_average_grade(student_grades):
# Write code hereAll lessons in Dictionary in Python
2Operations
Create DictionaryAccessing ItemsChange ValuesAdding ItemsRemoving ItemsCheck if a key existsLoop Through a Dictionary