These are 3 dicts I made each with the 4 same keys but of course different values.
lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}
I stored the dicts in a list.
students = [lloyd, alice, tyler]
What I'd like to do is loop through the list and display each like so:
"""
student's Name: val
student's Homework: val
student's Quizzes: val
student's Tests: val
"""
I was thinking a for loop would do the trick for student in students:
and I could store each in a empty dict current = {}
but after that is where I get lost. I was going to use getitem but I didn't think that would work.
Thanks in advance
You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration.
In Python, to iterate the dictionary ( dict ) with a for loop, use keys() , values() , items() methods. You can also get a list of all keys and values in the dictionary with those methods and list() . Use the following dictionary as an example. You can iterate keys by using the dictionary object directly in a for loop.
You can do this:
students = [lloyd, alice, tyler]
def print_student(student):
print("""
Student's name: {name}
Student's homework: {homework}
Student's quizzes: {quizzes}
Student's tests: {tests}
""".format(**student)) # unpack the dictionary
for std in students:
print_student(std)
Use loop below to display all students data without hardcoding keys:
# ...
# Defining of lloyd, alice, tyler
# ...
students = [lloyd, alice, tyler]
for student in students:
for key, value in student.items():
print("Student's {}: {}".format(key, value))
Good Luck !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With