Python从其他dict列表中的dict列表中查找元素

时间:2017-04-08 10:05:18

标签: python dictionary

我有两个字典列表。

    students = [{'lastname': 'JAKUB', 'id': '92051048757', 'name': 'BAJOREK'}, 
{'lastname': 'MARIANNA', 'id': '92051861424', 'name': 'SLOTARZ'}, {'lastname':
 'SZYMON', 'id': '92052033215', 'name': 'WNUK'}, {'lastname': 'WOJCIECH', 'id':
 '92052877491', 'name': 'LESKO'}]

并且

house = [{'id_pok': '2', 'id': '92051048757'}, {'id_pok': '24', 'id': '92051861424'}]

如何找到id匹配的词典匹配列表中不存在的元素?

输出

output = [{'lastname':
 'SZYMON', 'id': '92052033215', 'name': 'WNUK'}]

我尝试那样做

for student in students:

    for home in house:

        if student['id'] != home['id']:

            print student

但这只是重复列表

3 个答案:

答案 0 :(得分:1)

您的代码无法正常工作的原因是,如果house_idstudent_id不匹配,则student将被打印。您需要更多逻辑或any功能:

for student in students:
    if not any (student['id'] == home['id'] for home in house):
        print(student)

输出:

{'lastname': 'SZYMON', 'id': '92052033215', 'name': 'WNUK'}
{'lastname': 'WOJCIECH', 'id': '92052877491', 'name': 'LESKO'}

更有效的解决方案是保留set个house_id,并找到其ID不包含在此套装中的学生:

students = [{'lastname': 'JAKUB', 'id': '92051048757', 'name': 'BAJOREK'},
{'lastname': 'MARIANNA', 'id': '92051861424', 'name': 'SLOTARZ'}, {'lastname':
 'SZYMON', 'id': '92052033215', 'name': 'WNUK'}, {'lastname': 'WOJCIECH', 'id':
 '92052877491', 'name': 'LESKO'}]

house = [{'id_pok': '2', 'id': '92051048757'}, {'id_pok': '24', 'id': '92051861424'}]

house_ids = set(house_dict['id'] for house_dict in house)
result = [student for student in students if student['id'] not in house_ids]

print(result)

输出:

[{'lastname': 'SZYMON', 'id': '92052033215', 'name': 'WNUK'}, {'lastname': 'WOJCIECH', 'id': '92052877491', 'name': 'LESKO'}]

请注意,2名学生符合您的说明。

使用set enter link description here的原因是它允许比列表更快的查找。

答案 1 :(得分:0)

student_ids = set(d.get('id') for d in students)
house_ids = set(d.get('id') for d in house)

ids_not_in_house = student_ids ^ house_ids

答案 2 :(得分:0)

students = [{'lastname': 'JAKUB', 'id': '92051048757', 'name': 'BAJOREK'}, 
{'lastname': 'MARIANNA', 'id': '92051861424', 'name': 'SLOTARZ'}, {'lastname':
 'SZYMON', 'id': '92052033215', 'name': 'WNUK'}, {'lastname': 'WOJCIECH', 'id':
 '92052877491', 'name': 'LESKO'}]

house = [{'id_pok': '2', 'id': '92051048757'}, {'id_pok': '24', 'id': '92051861424'}]

s = {item['id'] for item in students}
h = {item['id'] for item in house}

not_in_house_ids = s.difference(h)
not_in_house_items = [x for x in students if x['id'] in not_in_house_ids]
print (not_in_house_items)

>>>[{'name': 'WNUK', 'lastname': 'SZYMON', 'id': '92052033215'}, {'name': 'LESKO', 'lastname': 'WOJCIECH', 'id': '92052877491'}]