Difference between a set and a view

前端 未结 1 801
你的背包
你的背包 2021-01-24 17:06

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

1条回答
  •  孤独总比滥情好
    2021-01-24 17:43

    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 explicit set(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 new set 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.

    0 讨论(0)
提交回复
热议问题