Easy Tutorial
❮ Python Func Zip Ref Set Isdisjoint ❯

Python3 Dictionary keys() Method

Python3 Dictionary


Description

The Python3 dictionary keys() 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 in the dictionary are reflected in the view objects.

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.

Note: Python2.x returns lists directly.

Syntax

The syntax for the keys() method is:

dict.keys()

Parameters

Return Value

Returns a view object.

Example

The following example demonstrates the use of the keys() 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 objects converted to lists also change accordingly
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(keys)
['bacon', 'spam']

Python3 Dictionary

❮ Python Func Zip Ref Set Isdisjoint ❯