繁体   English   中英

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

[英]Python find element from list of dict in other list of dict

我有两个字典。

    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

但这只是重复列表

您的代码不起作用的原因是,如果有不匹配student_id house_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的原因是,它允许查找比列表快得多。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM