Python3 Dictionary keys() Method

Python3 字典Python3 Dictionary


Description

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

dict.keys()、dict.values()anddict.items()What is returned is a view object, which provides a dynamic view of the dictionary's entities. This means that when the dictionary changes, the view changes accordingly.

The view object is not a list and does not support indexing. You can use list() to convert it to a list.

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

Note:Python2.x directly returns a list.

Syntax

The syntax of the keys() method:

dict.keys()

Parameters

  • NA。

Return Value

Returns a view object.

Example

The following example demonstrates how to use the keys() 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]

>>> # The view object is dynamic and is affected by dictionary changes. In the following example, the dictionary's key is deleted, and the view object, after being converted to a list, also changes accordingly.
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(keys)
['bacon', 'spam']

Python3 字典Python3 Dictionary

Other Extensions