Dictionary view objects vs sets

Question:

I have been reading about these dictionary view objects that are returned by the likes of dict.keys(), including the posts on here about the subject. I understand they act as windows to the dictionary’s contents without storing a copy of said contents explicitly and in so are more efficient than dynamically updating a list of keys. I also found they are containers (allow use of in operator) but are not sequences (not indexable), although they are iterable.

Overall this sounds to me like a set, since they have access to the dictionary’s hash table they even offer the use of set-like operations like intersection/difference. One difference I can think of is that a set, while mutable like these view objects, can only store immutable (and therefore hashable) objects.

However, since a dictionary value doesn’t have to be immutable, the values and items view objects are essentially sets with mutable contents, expectedly not supportive of set-like operations (subtraction/intersection). This makes me sceptical of considering these view objects as "a set with a reference to the dictionary".

My question is: are these view objects entirely different to sets but happen to have similar properties? Or are they implemented using sets? Any other major differences between the two? And most importantly – can it be damaging to consider them as "basically sets"?

Asked By: Ozz

||

Answers:

The implicit point of your comparison is that dict.keys() and set elements can’t have duplicates. However, the set-like Dictionary view obtained from the keys still retains order, while the set does not.

Duplicate dictionary keys:

If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.

Duplicate set elements:

A set object is an unordered collection of distinct hashable objects.

From the above, sets are unordered while in the current Python version dictionaries maintain insertion order:

Changed in version 3.7: Dictionary order is guaranteed to be insertion order.

Because dictionaries have an insertion order they can be reversed, while such operation in a set would be meaningless:

Dictionaries and dictionary views are reversible.

Finally, a set can be altered, deleted and inserted from. A Dictionary view object only allows looking at contents, not changing them.

My question is, are these view objects entirely different to sets but happen to have similar properties? Or are they implemented using sets?

The documentation makes no claim about implementation details.

Any other major differences between the two?

The documentations state the difference between "Keys views" and "items view" or "values views".

Keys views are set-like (…)

If all values are hashable, so that (key, value) pairs are unique and hashable, then the items view is also set-like.

(Values views are not treated as set-like (…))

Answered By: bad_coder