0

I'd like to compare the dicts by content, so I thought this can be done by creating an unordered hash of the item tuples.

What is the most elegant solution for that?

I was thinking about XORing all individual hashes, but maybe there is another ready-made solution?

EDIT: I have nested data structures. Some classes contain dicts. These classes can be aggregated to sets. So to compare the sets with the predefined set comparison I have to implement both __eq__ (which is easy) and __hash__ (which is my question) for my dict-classes?!

Gere
  • 12,075
  • 18
  • 62
  • 94
  • 4
    I do not follow what you are trying to do. Could you give us some examples of comparisons you want to make? – Martijn Pieters Sep 25 '12 at 09:59
  • Possible duplicate of http://stackoverflow.com/questions/1165352/fast-comparison-between-two-python-dictionary ? – Hans Then Sep 25 '12 at 10:06
  • Are your classes immutable? `set` assumes the hash values of the elements do not change. – Janne Karila Sep 25 '12 at 11:40
  • @JanneKarila: Hmm, they aren't exactly immutable, but I only need the set comparison momentarily to compare an unordered set of my classes. – Gere Sep 25 '12 at 12:06

2 Answers2

2

To check that all values are the same for overlapping keys, one of the following (depending on Python version) and style:

if all(dict_a[key] == dict_b[key] for key in dict_a.viewkeys() & dict_b.viewkeys())

if all(dict_a[key] == dict_b[key] for key in set(dict_a) & set(dict_b))

To handle the "are they the same value" a bit more specifically...

for k, v in dict_a.iteritems():
    try:
        ov = dict_b[k]
    except KeyError as e:
        continue
    if v == ov: 
        pass # or whatever
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • 1
    @BurhanKhalid That's what is being used in the 2nd example - the first example is taking advantage of the `dict_keys` object (which can behave set-ish ) returned by `.viewkeys()` - so not quite sure what your comment means? – Jon Clements Sep 25 '12 at 10:39
0

See documentation for Mapping Type.. You have already got operators defined to do various operations on Dictionary..

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525