Reputation: 47
I have searched the previous posts and have not found one where the person asking is doing quite what I'm trying to do:
I am trying to look through two separate dictionaries and find instances where the keys are the same, but the values are different. The dictionaries are not the same size. When I find matching keys that have different values, I want to add just the keys to a list as I will not need the values anymore.
Right now I am doing this. It is horribly inefficient, but is ok for 200-ish items. I have some dictionaries that are over 200,000 items, though, and that is where this becomes a major problem:
for sourceKey, sourceValue in sourceDict.iteritems():
for targetKey, targetValue in targetDict.iteritems():
if targetKey == sourceKey:
if targetValue != sourceValue:
diffList.append(sourceKey)
Is there a way to do this at all? I am using Python 2.6.
Upvotes: 1
Views: 1017
Reputation: 133764
[k for k in source_dict if target_dict.get(k, object()) != source_dict[k]]
Upvotes: 0
Reputation: 77197
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)
As DSM noted in his (now deleted) answer, you can do this with a list comprehension or generator:
(k for k in set(sourceDict).intersection(targetDict) if sourceDict[key] != targetDict[key])
Upvotes: 3
Reputation: 1334
1-liner: [key for key in set(sourceDict).intersection(targetDict) if sourceDict[key] != targetDict[key]]
Upvotes: 0