Python - 两个(略有不同)JSON 数组比较

标签 python python-2.7

我需要比较下面的两个 JSON 数组,并最终得到下面的 emails_new 结果...我发现的问题是其中一个数组有一个额外的键/值对,我在更新的数组中需要它。很难匹配。

本质上; “如果 emails_exist 中的任何电子邮件出现在 emails_all 中,请勿将其包含在 emails_new 中”

现有数组

emails_all = [{'email': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6b050e1c2b0e060a020745080406" rel="noreferrer noopener nofollow">[email protected]</a>', 'first_name': 'New Name'}, {'email': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9cf9e4f5efe8efdcf9f1fdf5f0b2fff3f1" rel="noreferrer noopener nofollow">[email protected]</a>', 'first_name': 'Exists Name'}]

emails_exist = [{'email': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3d6cbdac0c7c0f3d6ded2dadf9dd0dcde" rel="noreferrer noopener nofollow">[email protected]</a>'}]

emails_all 中删除所有 emails_exist 值,我只想构建一个列表来显示 中未出现的电子邮件的 email/first_name >emails_exist ...类似于下面的emails_new

输出

emails_new = [{'email': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aec0cbd9eecbc3cfc7c280cdc1c3" rel="noreferrer noopener nofollow">[email protected]</a>', 'first_name': 'New'}]

可能值得注意的是:这些 JSON 数组中每个数组最多可以包含 100 个项目。

最佳答案

只需使用一个简单的辅助函数

def contains(emails, email):                      
    for contained_email in emails:                   
        if email["email"] == contained_email["email"]: 
            return True                                 
    return False                                    

emails_new = [email for email in emails_all if not contains(emails_exist, email)]

关于Python - 两个(略有不同)JSON 数组比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50550433/

相关文章:

python - 如果新元组不在嵌套元组中,如何递归添加它?

python - Paraview:更改渲染窗口中轴的纵横比

python - Python 中的连接单元测试

python - 在python脚本中设置环境变量

python - shell 命令因 Python 中的 subprocess.call() 而失败

从嵌套字典生成列表的 Pythonic 方法

PHP 与应用程序服务器?

python-2.7 - Python 电子邮件仅在第一行丢失换行符

python - 在python中使用相同签名的方法重载

python - 为什么 `x = x` 仅在函数内部定义时才在 Python 类中给出错误?