1

I'm comparing 2 dictionaries in Python, loadedAgreement and latestDBAgreement. I know from this thread that a simple == or != can be used for dictionary comparison.

My dictionaries come out as unequal, and to get the diffs, I used the approach recommended here:

value = { k : second_dict[k] for k in set(second_dict) - set(first_dict) }

from both sides. But when I do this from both sides, both results are empty {}. So why are the dictionaries still unequal?

diffvalues1 = { k : latestDBAgreement[k] for k in set(latestDBAgreement) - set(loadedAgreement) }
diffvalues2 = { k : loadedAgreement[k] for k in set(loadedAgreement) - set(latestDBAgreement) }

As you can see in the debugger, the code dropped into the != section, but both diffs are empty.

enter image description here

gene b.
  • 10,512
  • 21
  • 115
  • 227
  • https://stackoverflow.com/questions/32815640/how-to-get-the-difference-between-two-dictionaries-in-python/32815681#comment84083883_32815681 - use the symmetric difference answer instead. – jonrsharpe Jun 07 '22 at 16:26
  • I did it from *both sides* . I did see that comment, so I'm aware of it: it's in the code. Did you see the phrase "both sides" ? – gene b. Jun 07 '22 at 16:27
  • 4
    Your diff code is only comparing the *keys* of the two dicts. It won't show if the same key has different values in each one. – jasonharper Jun 07 '22 at 16:28
  • So how do I get the different values as well? – gene b. Jun 07 '22 at 16:29
  • 1
    You can use `set(d1.items()) - set(d2.items())` – Barmar Jun 07 '22 at 16:29
  • And does this need to be done from both sides as well? – gene b. Jun 07 '22 at 16:30
  • 1
    Yes, you should do it both ways. – Barmar Jun 07 '22 at 16:30
  • 1
    If you use the top-voted answer (rather than just the _accepted_ one) on the linked post, it does both keys and values from both sides, unless there are issues with hashing. – jonrsharpe Jun 07 '22 at 16:32
  • Thanks. Does `set(d1.items()) ^ set(d2.items())` also include the key differences? For completeness, it needs to be both values and keys. That should be part of that answer too. – gene b. Jun 07 '22 at 16:38
  • 1
    In Python dictionaries, items are (key, value) pairs. – jonrsharpe Jun 07 '22 at 16:42

1 Answers1

1

Dicts can also differ in values. To see which, you can do something like this:

{
    k: (v, latestDBAgreement[k])
    for k, v in loadedAgreement.items()
    if v != latestDBAgreement[k]}

(This of course assumes that the keys are the same, so it doesn't generalize.)

wjandrea
  • 28,235
  • 9
  • 60
  • 81