you need to change a little list2to get a quick search. I would make setof him
list1 = [{'user_id':23, 'user_name':'John','age':30},
{'user_id':24, 'user_name':'Shaun','age':31},
{'user_id':25, 'user_name':'Johny','age':32}]
list2 =[{'user_id':23},
{'user_id':25}]
list2_ids = {d['user_id'] for d in list2}
then build list3using list filtering. In this case, it in list2_idsis very fast because it uses a search from set, rather than a linear search:
list3 = [x for x in list1 if x['user_id'] in list2_ids]
print(list3)
result:
[{'user_id': 23, 'user_name': 'John', 'age': 30}, {'user_id': 25, 'user_name': 'Johny', 'age': 32}]
source
share