Difference between set and view

I've been learning Python for about a month now and I came across a discussion of views and sets. The book I am using, Learning Python, says views are iterable and have their objects in the same order as a dictionary, but views also support set operations.

It seems to me that they can do whatever they do. It looks like a duck, charlatans are like a duck and allow operations like a duck. Why do sets and views then separate object types?

Also, I searched for "Set View Python Difference" for duplicate questions and couldn't find one.

+1


source to share


1 answer


Only a dictionary of a dictionary is dict.keys()

always a collection (in the sense that it behaves like a collection, but with a live representation of the dictionary).

The view is dict.values()

never fixed, since values ​​cannot be guaranteed to be unique, and hash is also not guaranteed (a requirement for sets). You would also need to calculate all the hashes ahead of time once you create a dictionary of values ​​view, a potentially very expensive operation. You can always use explicit set(dictionary.values())

in this case.



This leaves a view dict.items()

that is mostly a set if all values ​​are hashed; because when you create an intersection or join or other new set from a view, you must create a new object set

that requires the entire key and value pair to be hashable; you can no longer guarantee that only the keys will be unique in such cases.

Also see the Dictionary View Objects documentation .

+2


source







All Articles