Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through a list that contains dicts and displaying it a certain way

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

like image 527
ChrisSlightGhost Avatar asked Feb 01 '16 15:02

ChrisSlightGhost


People also ask

How do you loop through a list of elements?

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.

How do I iterate a list of dictionaries?

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.


2 Answers

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)
like image 188
Mohammed Aouf Zouag Avatar answered Oct 14 '22 01:10

Mohammed Aouf Zouag


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 !

like image 43
Andriy Ivaneyko Avatar answered Oct 13 '22 23:10

Andriy Ivaneyko