简体   繁体   中英

Compare values from two different dictionaries in Python?

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.

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])
[k for k in source_dict if target_dict.get(k, object()) != source_dict[k]]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM