Easy Tutorial
❮ Ref Math Copysign Python String Isdecimal ❯

Python3 Dictionary values() Method

Python3 Dictionary


Description

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

dict.keys(), dict.values(), and dict.items() all return view objects, which provide a dynamic view of the dictionary entries. This means that changes to the dictionary are reflected in the view.

View objects are not lists and do not support indexing. They can be converted to lists using list().

We cannot modify view objects directly because they are read-only.

Syntax

The syntax for the values() method is:

dict.values()

Parameters

Return Value

Returns a view object.

Example

The following example demonstrates the use of the values() method:

>>> 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)      # Convert to list using list()
['eggs', 'sausage', 'bacon', 'spam']
>>> list(values)
[2, 1, 1, 500]

>>> # View objects are dynamic and affected by dictionary changes. The following deletes keys from the dictionary, and the view object, when converted to a list, reflects these changes.
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(values)
[1, 500]
>>> # Comparing two dict.values() returns False
>>> d = {'a': 1}
>>> d.values() == d.values()
False

Python3 Dictionary

❮ Ref Math Copysign Python String Isdecimal ❯