Inconsistent behaviour between dict.items and dict.values

做~自己de王妃 提交于 2019-12-02 02:32:06
Martijn Pieters

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).

The reason is that it's not implemented in the dict_values type or because the dict_values class specifically disallows it.

Since your values are generally a non-unique list of items it's not a great idea to convert it to a set. If you do want that, just manually convert it. My assumption is that it's disallowed since it's generally a bad idea as it can cause data loss.

Because in a dict you can not have repeated keys values, but you can have repeated values values:

>>> d = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}
>>> d.keys()
[0, 1, 2, 3, 4]
>>> d.values()
[0, 0, 0, 0, 0]
>>> d.items()
[(0, 0), (1, 0), (2, 0), (3, 0), (4, 0)]

The keys() method return something like cuacks and ducks like a set because you can not have repeated keys on the dict, but you can have repeated values on values(). That's why keys cuacks and ducks like a set but values cuacks and ducks like a list.

If you are coding in leetcode, then you can make it by changing the result from

return res_dic.values()

to

return list(res_dic.values())
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!