I've been learning Python for about over a month, and I ran into a discussion about views and sets. The book I'm using, Learning Python, says that views are iterables and have their objects in the same order that the dictionary does, but views also supports set operations.
It seems to me that they can do everything sets do. It looks like a duck, quacks like a duck, and allow set operations like a duck. Why are sets and views then separate types of objects?
Also, I searched 'Set View Python Difference' to look for duplicate questions and couldn't find any.
Only the
dict.keys()
dictionary view is always a set (insofar that it behaves like a set, but one with a live view of the dictionary).The
dict.values()
view is never a set, as the values cannot be guaranteed to be unique and the are also not guaranteed to be hashable (a requirement for sets). You'd also have to calculate all hashes up-front the moment you create the values dictionary view, a potentially very expensive operation. You can always use an explicitset(dictionary.values())
in that case.That leaves the
dict.items()
view, which is mostly a set, provided all values are hashable; that's because when you create an intersection or union or other new set from the view, you have to produce a newset
object, which requires that the whole key-value pair is hashable; you can no longer guarantee that just the keys will be unique in such cases.Also see the Dictionary View Objects documentation.