Skip to main content

keys()

The keys() method in Python dictionary objects returns a view object that displays a list of all the keys in the dictionary. This view object can then be used to iterate over the keys, retrieve specific keys, or convert the view into a list of keys.

Parameter Values

This function does not accept any parameters.

Return Values

The keys() method in Python returns a view object that displays a list of all keys.

How to Use keys() in Python

Example 1:

The keys() method returns a view object that displays a list of all the keys in the dictionary.

```python
# Using keys() method
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys = my_dict.keys()
print(keys)
```
Example 2:

The view object is dynamic and reflects changes made to the dictionary.

```python
# Modifying the dictionary and checking keys()
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys = my_dict.keys()
my_dict['d'] = 4
print(keys)
```
Example 3:

The keys() method does not return a traditional list, but it can be converted into one using the list() function.

```python
# Converting keys view object to list
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys = list(my_dict.keys())
print(keys)
```