Python3 Dictionary values() Method

Python3 字典Python3 Dictionary


Description

The Python3 Dictionary values() method returns a view object.

dict.keys(), dict.values(), anddict.items()all return view objects, which provide a dynamic view of the dictionary entries. This means that when the dictionary changes, the view changes accordingly.

View objects are not lists and do not support indexing. You can use list() to convert them to lists.

We cannot make any modifications to view objects, because the view objects of a dictionary are read-only.

Syntax

values() method syntax:

dict.values()

Parameters

  • NA。

Return Value

Returns a view object.

Examples

The following example demonstrates how to use the values() method:

Example

>>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
>>> keys = dishes.keys()
>>> values = dishes.values()

>>> # iteration
>>> n = 0
>>> for val in values:
...     n += val
>>> print(n)
504

>>> # keys and values are iterated in the same order (insertion order)
>>> list(keys)     # use list() to convert to a list
['eggs', 'sausage', 'bacon', 'spam']
>>> list(values)
[2, 1, 1, 500]

>>> # View objects are dynamic and affected by dictionary changes. The following removes a key from the dictionary, and the view object changes accordingly after being converted to a list.
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(values)
[1, 500]
>>> # Comparing two identical dict.values() objects always returns False
>>> d = {'a': 1}
>>> d.values() == d.values()
False

Python3 字典Python3 Dictionary

Other Extensions