I have found that comparing the results of the keys()
and values()
methods of the dict
built-in to themselves results in inconsistent results:
instance = {'one': 1}
instance.values() == instance.values() # Returns False
instance.keys() == instance.keys() # Returns True
Running the above code in Python 2.7 will return True for both calls, leading me to believe that there is some implementation detail in Python 3's dict_values
that causes this strange behaviour.
Is there a reason for this behaviour or have i stumbled upon some obscure bug?
The short answer:
class dict_values
doesn't have a__eq__
method implemented, butclass dict_keys
does:Therefore, the
d.values()
's==
comparison evaluates toFalse
.The longer answer of why it wasn't implemented is a different one and can be seen with a little more digging on the documentation of dict-view objects. This part seems especially relevant (emphasis mine):
Since keys must be unique, it makes sense that they are set-like and are supported with the class operations of
collections.Set
. Values are not set-like due to non-uniqueness.In Python 2.7 however,
d.keys()
andd.values()
both return alist
per the documentation therefore this restriction does not apply. Since they are both the same type of object, it makes sense the same operation will work on both. If you usedviewkeys
andviewvalues
as mentioned in the documentation of dict-view objects in Python2.7, then you can expect similar behaviour: