Note: code examples in python3, but the question stands for python2 as well (replacing .keys
with .viewkeys
, etc)
dict
objects provide view methods which (sometimes) support set operations:
>>> {'a': 0, 'b': 1}.keys() & {'a'}
{'a'}
>>> {'a': 0, 'b': 1}.items() & {('a', 0)}
{('a', 0)}
But the values view does not support set operators:
>>> {'a': 0, 'b': 1}.values() & {0}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'dict_values' and 'set'
I understand that a dict value can be a non-hashable object, so it is not always possible to make a set of the values, however the same is true for dict.items
, and here the set operations only fail at runtime for .items
once there is an unhashable type in the dict, whereas the set operation for .values
fails immediately.
The docs mention that Values views are not treated as set-like since the entries are generally not unique, but this doesn't seem to be a convincing reason - python doesn't for example prevent you from creating a set literal like {0, 0, 1, 2}
.
What is the real reason for this inconsistency in behaviour?