【发布时间】:2020-11-29 11:04:23
【问题描述】:
我有两个字典列表,如下所示:
incidents = [
{
"incidentId": "RWS03_949563",
"incidentState": "REGISTERED"
},
{
"incidentId": "RWS03_949565",
"incidentState": "REGISTERED"
}
]
incidents_db = [
{
"incidentId": "RWS03_949563",
"incidentState": "PENDING"
},
{
"incidentId": "RWS03_949565",
"incidentState": "PENDING"
}
]
我想比较 incidentId 并返回 non_match。这是我现在的代码,但它只返回两个项目,因为它比较整个项目而不是只比较 incidentId。有什么好的方法可以做到这一点?
non_match = []
for i in incidents:
if i not in incidents_db:
non_match.append(i)
【问题讨论】:
-
如果两个字典列表中的
incidentId具有相同的值,你的代码的目的是什么? -
这只是一个唯一的 ID。我的数据库中有一些“事件”,我每 5 分钟就会收到新事件。我需要将这两个列表相互比较。当数据库列表中不存在事件ID时,我需要添加项目@ombk
-
所以您实际上希望代码检查
incidents中的新实例是否还没有在incidents_db中并将其添加到那里? -
是的。但有时
incidentState与上面的示例不同。但我只关心incidentId。如果来自incidents的实例已经在incidents_db中具有相同的ID,我不需要添加项目@ombk -
检查我发送的代码,它解决了你的问题
标签: python dictionary compare