Deep comparison of dicts - cmp() versus ==?

Victor Hooi victorhooi at gmail.com
Thu Mar 19 22:57:11 EDT 2015


Hi Ben,

When I said "deep", I meant, as in, to an arbitrary level of nesting (i.e. dicts, containing dicts, containing dicts etc) - sorry if I got the terminology wrong.

The two dicts weren't equal by intention - the idea was that a comparison operator would return "False" for those two.

I was just curious why cmp() was phased out (as in, were there cases where "==" was better) - but if functionality they're the same, and it's just a nomenclature thing, that's also fine =).

Finally, so cmp()/== return true/false for comparison - just noticed this which actually prints out diff-style comparisons:

https://pypi.python.org/pypi/datadiff

Cheers,
Victor


On Friday, 20 March 2015 13:33:52 UTC+11, Ben Finney  wrote:
> Victor Hooi <victorhooi at gmail.com> writes:
> 
> > What is the currently most Pythonic way for doing deep comparisons
> > between dicts?
> 
> What distinction do you intend by saying "deep comparison"? As
> contrasted with what?
> 
> > For example, say you have the following two dictionaries
> >
> > a = {
> >         'bob': { 'full_name': 'bob jones', 'age': 4, 'hobbies': ['hockey', 'tennis'], 'parents': { 'mother': 'mary', 'father', 'mike'}},
> >         'james': { 'full_name': 'james joyce', 'age': 6, 'hobbies': [],}
> > }
> >
> > b = {
> >         'bob': { 'full_name': 'bob jones', 'age': 4, 'hobbies': ['hockey', 'tennis']},
> >         'james': { 'full_name': 'james joyce', 'age': 5, 'hobbies': []}
> > }
> 
> Those two dicts are not equal. How would your intended "deep comparison"
> behave for those two values?
> 
> > However, this page seems to imply that cmp() is deprecated?
> > https://docs.python.org/3/whatsnew/3.0.html#ordering-comparisons
> 
> It is, yes.
> 
> > Should we just be using the equality operator ("==") instead then? E.g.:
> >
> > a == b
> 
> Yes. That is a comparison that would return False for comparing the
> above two values. Would you expect different behaviour?
> 
> > What is the reason for this?
> 
> I don't really understand. 'cmp' is deprecated, and you can compare two
> dicts with the built-in operators. That's the reason; are you expecting
> some other reason?
> 
> > Or is there a better way to do this?
> 
> I don't really know what it is you want to do. What behaviour different
> from the built-in comparison operators do you want?
> 
> -- 
>  \         "I went over to the neighbor's and asked to borrow a cup of |
>   `\       salt. 'What are you making?' 'A salt lick.'" --Steven Wright |
> _o__)                                                                  |
> Ben Finney



More information about the Python-list mailing list