Home > Software engineering >  Loop through list of dictionaries if certain values to create a new list
Loop through list of dictionaries if certain values to create a new list

Time:10-21

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.

CodePudding user response:

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.

CodePudding user response:

student_roster[i][key] == "Math" or "Science"

This will alwayse evaluate True because the interpreter does not compare your entry to both "Math" and "Science", but only to "Math" and will then evaluate the expression

if "Science"

as a standalone thing.

You have to do

student_roster[i][key] == "Math" or student_roster[i][key] == "Science"

or

student_roster[i][key] in ["Math", "Science"]

CodePudding user response:

You can do this in one line in Python...

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"
   }]

new_list = [student for student in student_roster if (student['favorite_subject'] == 'Math' or student['favorite_subject'] == 'Science')]

I'm creating a new list by adding a condition.

Your code will work if you change this line:

if student_roster[i][key] == "Math" or "Science":

to this:

if student_roster[i][key] == "Math" or student_roster[i][key] == "Science":

... to explain the one liner:

new_list = [<new-item> for <potentially-new-item> in <existing-list> if <condition-needed-to-make-potential-item-the-new-item>]

CodePudding user response:

Put the condition in a container (set is recommended here) and use in for the check.

stems = [d["name"] for d in student_roster for v in d.values() if v in {"Math", "Science"}]
  • Related