eod
eod

Reputation: 29

Compare two separate dictionary values

I'm new to Python and looking to figure out how to code this properly. I have two lists of dictionaries and I'm trying to find if the student ID exists in a string that can contain the student ID and other information. My badly formed approach:

confirmed_students = [{'div_school_id': 'as-dh23d7ashdh'}, {'div_school_id': 'asdas-3sdfasd'}, {'div_school_id': 'i4-d9asjcg'}] 

students = [{'student_id': 'dh23d7ashdh','name': 'First Last','student_grade': '4'}, {'student_id':'3sdfasd', 'name':...}] 

bad_list = []
for student in students:
    if student['student_id'] not in confirmed_students:
        bad_list.append({"id": student['student_id'], "name": student['name'], "grade": student['student_grade']})

What would be the proper way to do this? Should I iterate through the list of dicts confirmed_students in the same loop? I only need to know if the student_id from the list of dicts called students exists at all in the list of dicts called confirmed_students and add the relevant info.

Upvotes: 0

Views: 68

Answers (2)

Will
Will

Reputation: 1551

A brute force way of getting there (and probably not the most efficient) is to loop over both lists. Check if each element of students is in confirmed_students.

Firstly, you need a way of knowing if the student is in the confirmed_students list. There must be a key to match on. Looking at your data it seems as if confirmed_students has div_school_id that is some kind of composite of the student_id and some prefix.

# looking at one confirmed student as an example
confirmed_student = confirmed_students[0]
# confirmed_student = {'div_school_id': 'as-dh23d7ashdh'}
# we need to split the id on the '-' and keep the last part
confirmed_student_id = confirmed_student['div_school_id'].split("-")[1]
# gives us confirmed_student_id as 'dh23d7ashdh' which looks right?

# now we loop over your students and see if their id is in confirmed_students
bad_list = []
for student in students:
    for confirmed_student in confirmed_students:
        confirmed_student_id = confirmed_student['div_school_id'].split("-")[1]
        if student["student_id"] == confirmed_student_id:
            bad_list.append({"id": student['student_id'], "name": student['name'], "grade": student.get('student_grade', '')})
            # break from the inner loop and continue the outer loop
            # because we only need the first match
            break

Upvotes: 1

Tarifazo
Tarifazo

Reputation: 4343

You can build the list using list comprehension:

bad_list = [{k: student[v] for k, v in zip(('id', 'name', 'grade'), ('student_id', 'name', 'student_grade'))} for student in students if student['student_id'] not in confirmed_students]

Sidenote: I suggest you define the students as a dictionary using the student_id as key (assuming it is unique, which it should). It will make it much more easier to perform comparisons like the one you want.

Upvotes: 1

Related Questions