Inconsistent behaviour between dict.items and dict.values

前端 未结 4 1925
北海茫月
北海茫月 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:33

    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.

提交回复
热议问题