簡體   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