@Danny, you can also get the expected output with just 1 line of code using Python's list comprehension, map(), filter(), lambda function etc. as the below code examples shows.
Please comment if you face any problem while reading & understanding my code.
Check Lambda, filter(), map() and List comprehension. It's really good to use these concepts in programming.
1 line code
emails_new = list(filter(lambda email_all_dict: True if sum(list(map(lambda email_exist_dict: True if email_exist_dict["email"] == email_all_dict['email'] else False, emails_exist))) == 0 else False, emails_all))
Now have a look at the below code examples one by one.
Example 1
emails_all = [{'email': '[email protected]', 'first_name': 'New Name'}, {'email': '[email protected]', 'first_name': 'Exists Name'}]
emails_exist = [{'email': '[email protected]'}]
emails_new = list(filter(lambda email_all_dict: True if sum(list(map(lambda email_exist_dict: True if email_exist_dict["email"] == email_all_dict['email'] else False, emails_exist))) == 0 else False, emails_all))
print(emails_new)
# [{'first_name': 'New Name', 'email': '[email protected]'}]
Example 2
emails_all = [
{'email': '[email protected]', 'first_name': 'New Name1'},
{'email': '[email protected]', 'first_name': 'Exists Name1'},
{'email': '[email protected]', 'first_name': 'Exists Name2'},
{'email': '[email protected]', 'first_name': 'Exists Name5'},
{'email': '[email protected]', 'first_name': 'Exists Name6'},
{'email': '[email protected]', 'first_name': 'New Name9'},
{'email': '[email protected]', 'first_name': 'Exists Name7'},
{'email': '[email protected]', 'first_name': 'Exists Name8'},
{'email': '[email protected]', 'first_name': 'Exists Name4'},
{'email': '[email protected]', 'first_name': 'New Name4'},
{'email': '[email protected]', 'first_name': 'New Name2'},
{'email': '[email protected]', 'first_name': 'Exists Name3'}
]
emails_exist = [
{'email': '[email protected]'}, # Does not exist
{'email': '[email protected]', 'first_name': 'Exists Name7'},
{'email': '[email protected]', 'first_name': 'Exists Name8'},
{'email': '[email protected]', 'first_name': 'Exists Name4'}
]
emails_new2 = list(filter(lambda email_all_dict: True if sum(list(map(lambda email_exist_dict: True if email_exist_dict["email"] == email_all_dict['email'] else False, emails_exist))) == 0 else False, emails_all))
# Pretty printing list
print(json.dumps(emails_new2, indent=4))
"""
[
{
"first_name": "New Name1",
"email": "[email protected]"
},
{
"first_name": "Exists Name1",
"email": "[email protected]"
},
{
"first_name": "Exists Name2",
"email": "[email protected]"
},
{
"first_name": "Exists Name5",
"email": "[email protected]"
},
{
"first_name": "Exists Name6",
"email": "[email protected]"
},
{
"first_name": "New Name9",
"email": "[email protected]"
},
{
"first_name": "New Name4",
"email": "[email protected]"
},
{
"first_name": "New Name2",
"email": "[email protected]"
},
{
"first_name": "Exists Name3",
"email": "[email protected]"
}
]
"""