Inconsistent behaviour between dict.items and dict.values

前端 未结 4 1927
北海茫月
北海茫月 2021-01-23 00:40

Note: code examples in python3, but the question stands for python2 as well (replacing .keys with .viewkeys, etc)<

4条回答
  •  無奈伤痛
    2021-01-23 01:30

    If we were to treat the values as a set, you'd make the values dictionary view a very costly object to produce. You have to calculate the hash of all values before you can use it as a set; you really don't want to do this for a large dictionary, especially if you don't know up front if all values are even hashable.

    As such, this is far better left as an explicit operation; if you want to treat the values as a set, explicitly make it a set:

    values = set(yourdict.values())
    

    The dict.items() behaviour stems from the fact that we know up-front that the keys at least are unique, so each (key, value) pair is unique too; under the covers you can delegate membership testing to the keys dictionary view.

    But as soon as you use set operations on that (intersection, union, etc.) you are creating a new set object, not a dictionary view. And for such a set object both elements in the (key, value) pair must be hashable, as the generic set type cannot make the same assumption about the keys, nor could you maintain that constraint (as {'a': 0}.items() & {('a', 1)} is perfectly legal but leads to duplicate keys).

提交回复
热议问题