
Syntax: Dict Iteration
Repeating operations on dictionary names and values.
In Python, we can iterate over dictionaries in multiple ways: either by keys, by values, or by both keys and values simultaneously.
Iterating Through Dictionary Keys
To iterate over keys in a dictionary, you can directly use a for loop on the dictionary.
user = {
"name": "Alice",
"email": "[email protected]",
"age": 24
}
for key in user:
print(key)
> "name"
> "email"
> "age"
Iterating Through Dictionary Values
To iterate over values in a dictionary, you can use the .values() method.
user = {
"name": "Alice",
"email": "[email protected]",
"age": 24
}
for value in user.values():
print(value)
> "Alice"
> "[email protected]"
> 24
Iterating Through Dictionary Keys and Values Simultaneously
To iterate over both keys and values in a dictionary, you can use the .items() method.
user = {
"name": "Alice",
"email": "[email protected]",
"age": 24
}
for key, value in user.items():
print(key, value)
> "name" "Alice"
> "email" "[email protected]"
> "age" 24
Practice: Adding a Dictionary's Values
-
Create a dictionary
scoreswith keys as student names and values as their corresponding scores. -
Use a
forloop to iterate overscoresand print each student name and their score. -
Calculate the average score of the students and print it.
HINT*: Click here for a hint
> Average score: 85.0
SOLUTION*: Click here for an example solution
scores = {
"Alice": 90,
"Bob": 80,
"Charlie": 85
}
total = 0
for score in scores.values():
total += score
print("Average score:", total / len(scores))
Practice: Iterating Through a Dictionary of Dictionaries
Imagine you have a dictionary student_data where each key is a student ID and the value is another dictionary containing that student's information: name, email, and GPA.
-
Create the
student_datadictionary with at least three students. -
Iterate over
student_dataand print each student's ID and name. -
Calculate the average GPA of the students and print it.
HINT*: Click here for a hint
> Average GPA: 3.5
SOLUTION*: Click here for an example solution
student_data = {
101: {"name": "Alice", "email": "[email protected]", "GPA": 3.6},
102: {"name": "Bob", "email": "[email protected]", "GPA": 3.4},
103: {"name": "Charlie", "email": "[email protected]", "GPA": 3.5}
}
total_GPA = 0
for student_id, info in student_data.items():
print(student_id, info["name"])
total_GPA += info["GPA"]
print("Average GPA:", total_GPA / len(student_data))
Awesome job! Understanding dictionary iteration is key to manipulating and analyzing data in Python.