I am working on a project off codecademy focusing on creating custom iterable classes and having trouble figuring out this section.
I have a list of dictionaries of students, example below:
student_roster = [
{
"name": "Karina M",
"age": 8,
"height": 48,
"favorite_subject": "Math",
"favorite_animal": "Dog"
},
{
"name": "Yori K",
"age": 7,
"height": 50,
"favorite_subject": "Art",
"favorite_animal": "Cat"
},
{
"name": "Alex C",
"age": 7,
"height": 47,
"favorite_subject": "Science",
"favorite_animal": "Cow"
}]
What I need to do is iterate through the dictionaries in this list, and if a particular student’s "favorite_subject" is either "Math" or "Science", I need to grab their name and add them to a separate list.
I have tried multiple options and but I seem to keep adding EVERYONE to my new list, as the dictionary, rather than just grabbing only the value of their name to add to a list.
The end goal is to have a list:
stem = [Karina M, Alex C, etc]
I have tried a number of attempts, but for example, my most recent attempt. This is within the custom class created:
def get_students_with_subject(self):
stem = []
for i in range(len(student_roster)):
for key, value in student_roster[i].items():
if student_roster[i][key] == "Math" or "Science":
stem.append(student_roster[i])
When this runs, however, I am just adding every dictionary in my list to the new, stem list and it’s not parsing out the specific values.
I have also appended the stem list with:
stem.append(student_roster[i][key])
But that then adds all values from all dictionaries to the list and I can’t figure out how to add JUST the names of JUST the dictionaries that included "favorite_subject" == "Math" or "Science"
I am still learning so any help would be very appreciated.
>Solution :
First lets simplify the dictionaries in order to get the important data only:
student_roster = [
{
"name": "Karina M",
"favorite_subject": "Math",
},
{
"name": "Yori K",
"favorite_subject": "Art",
},
{
"name": "Alex C",
"favorite_subject": "Science",
}
]
Now that we have done that, we can start working on implementing a proper solution. First, go ahead and declare a new list:
math_and_science_students = []
That is the list where you will be adding the names of all the students that like math or science. Now lets work on the loop:
for student in student_roster:
if student["favorite_subject"] in ["Math", "Science"]:
math_and_science_students.append(student["name"])
The in operator in this case will check if the student favorite subject is Math or Science. It essentially is the same as saying:
if student["favorite_subject"] == "Math" or student["favorite_subject"] == "Science"
just much shorter, cleaner and more dynamic.