1

我已经搜索了以前的帖子,但没有找到一个提问的人正在做我想做的事情:

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

现在我正在这样做。它的效率非常低,但对于 200 件左右的物品来说还可以。不过,我有一些超过 200,000 项的词典,这就是它成为主要问题的地方:

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

有没有办法做到这一点?我正在使用 Python 2.6。

4

3 回答 3

3
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 在他(现已删除)的答案中指出的那样,您可以使用列表理解或生成器来执行此操作:

(k for k in set(sourceDict).intersection(targetDict) if sourceDict[key] != targetDict[key])
于 2013-04-09T03:09:56.593 回答
0
[k for k in source_dict if target_dict.get(k, object()) != source_dict[k]]
于 2013-04-09T03:11:02.977 回答
0

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

于 2013-04-09T03:18:57.373 回答