Skip to content

Python Dictionary keys() method

  • by

In Python, the keys() method is a built-in method for dictionaries, which returns a dictionary view object containing all the keys of the dictionary. This method allows you to access the keys of the dictionary in a dynamic way, as it provides a view that reflects any changes made to the dictionary.

Syntax of the keys() method:

dictionary.keys()
  • dictionary: The dictionary for which you want to retrieve the keys.

The keys() method is called on a dictionary object and does not take any arguments inside the parentheses.

Python Dictionary keys() example

Simple example code.

# Creating a dictionary
fruit_counts = {
    'apple': 3,
    'banana': 2,
    'orange': 5,
    'grapes': 7
}

# Getting the keys of the dictionary using keys() method
keys_view = fruit_counts.keys()

# Printing the keys view
print(keys_view)

Output:

Python Dictionary keys() method

If you need to work with the keys as a list explicitly, you can convert the dictionary view into a list:

keys_list = list(fruits.keys())
print(keys_list)

Output: [‘apple’, ‘banana’, ‘orange’, ‘grapes’]

You can iterate through the dictionary view returned by the keys() method, or if you need to work with the keys explicitly as a list, you can convert the view to a list using the list() function.

Here’s an example demonstrating both approaches:

# Creating a dictionary
fruit_counts = {
    'apple': 3,
    'banana': 2,
    'orange': 5,
    'grapes': 7
}

# Getting the keys of the dictionary using keys() method
keys_view = fruit_counts.keys()

# Iterating through the keys view
print("Iterating through the keys view:")
for key in keys_view:
    print(key)

# Converting the keys view to a list
keys_list = list(fruit_counts.keys())

# Printing the keys list
print("\nKeys list:")
print(keys_list)

Output:

Iterating through the keys view:
apple
banana
orange
grapes

Keys list:
['apple', 'banana', 'orange', 'grapes']

In the first part of the example, we use a for loop to iterate through the dictionary view and print each key. In the second part, we convert the dictionary view to a list using the list() function, and then we print the keys as a list. Both methods allow you to access the keys of the dictionary for further processing or analysis.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading