比较Python中两个不同字典中的值?

2024-06-06 03:12:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经搜索了以前的帖子,但没有发现一篇帖子中的提问者正在做我想做的事情:

我试图通过两个独立的字典查找键相同但值不同的实例。这些字典的大小不一样。当我找到具有不同值的匹配键时,我只想将这些键添加到列表中,因为我不再需要这些值了。在

现在我正在做这个。它的效率非常低,但对于200个ish的项目来说还是可以的。不过,我有一些字典超过20万条,这就是问题所在:

    for sourceKey, sourceValue in sourceDict.iteritems():
         for targetKey, targetValue in targetDict.iteritems():
              if targetKey == sourceKey:
                   if targetValue != sourceValue:
                        diffList.append(sourceKey)

有没有办法做到这一点?我使用的是python2.6。在


Tags: 实例in列表forif字典事情帖子
3条回答
[k for k in source_dict if target_dict.get(k, object()) != source_dict[k]]
for key in set(sourceDict).intersection(targetDict):
    # Now we have only keys that occur in both dicts
    if sourceDict[key] != targetDict[key]:
        diffList.append(key)

正如DSM在其(现已删除)答案中指出的,您可以通过列表理解或生成器来实现:

^{pr2}$

1行:[key for key in set(sourceDict).intersection(targetDict) if sourceDict[key] != targetDict[key]]

相关问题 更多 >