1

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?!

4
  • 4
    I do not follow what you are trying to do. Could you give us some examples of comparisons you want to make? Commented Sep 25, 2012 at 9:59
  • Possible duplicate of stackoverflow.com/questions/1165352/… ? Commented Sep 25, 2012 at 10:06
  • Are your classes immutable? set assumes the hash values of the elements do not change. Commented Sep 25, 2012 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. Commented Sep 25, 2012 at 12:06

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

@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?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.