Python dictionary keys() method [With Examples]

In this Python article, we will explore the Python dictionary keys() method with examples and illustrate how to obtain the keys in a dictionary.

Dictionary keys() method in Python

Below are the topics that we are doing to discuss in this article:

  • Introduction to Python Dictionary keys() method
  • Syntax of the keys() method
  • Advantages of the keys() method
  • Purpose and use cases of the keys() method

Python Dictionary keys() method

The keys() method is a built-in Python function that retrieves the keys in a dictionary. It returns a view object that displays a Python list of all the keys.

This view object is dynamic, meaning that any changes made to the Python dictionary will be reflected in the view object.

Syntax:

dictionary.keys()

Here, ‘dictionary’ refers to the Python dictionary object we want to extract the keys from.

Advantages of using the keys() method

The Python keys() method offers several advantages when working with dictionaries:

  • It provides a dynamic view of the Python dictionary keys, reflecting any changes made to the dictionary.
  • It allows for easy iteration through the Python keys.
  • The view object can be converted to other Python data types like lists or tuples when required.

keys() method in Python Dictionary Examples

Let’s dive into simple examples to understand the keys() method:

Example#1 Getting the keys using the keys() method

Let’s use a simple example related to US states and their capitals to understand the Python keys() method:

us_states = {'California': 'Sacramento', 'Texas': 'Austin', 'Florida': 'Tallahassee'}
keys_view = us_states.keys()
print(keys_view)
  • In this example, we create a Python dictionary called 'us_states' containing three key-value pairs. Each key represents a US state, and its corresponding value is the state’s capital.
  • To retrieve the keys from the 'us_states' dictionary, we use the keys() method.
  • The 'keys_view' variable now holds a view object containing the keys.

Output:

Python dictionary keys method
Python dictionary keys method

Example#2 Iterating through dictionary keys

We can use the Python keys() method in conjunction with a for loop to iterate through the dictionary keys:

us_states = {'California': 'Sacramento', 'Texas': 'Austin', 'Florida': 'Tallahassee'}
for state in us_states.keys():
   print(state)
  • In this example, we show how to iterate through the keys of the 'us_states' Python dictionary using a for loop.
  • The for loop iterates over each key in the keys view object returned by the Python keys() method. In each iteration, the 'state' variable holds the current key, which is then printed.

Output:

Python dictionary keys method example
Python dictionary keys method example

Example#3 Converting the keys view object to other data types

In some cases, we might need to convert the keys view object to a different data type, such as a Python list or a tuple. We can easily achieve this using the Python list() or tuple() functions, respectively:

keys_list = list(us_states.keys())
keys_tuple = tuple(us_states.keys())

print(keys_list) 
print(keys_tuple) 

First, we convert the Python keys view object to a list and store it in the 'keys_list' variable. Then, we convert the keys view object to a Python tuple and store it in the 'keys_tuple' variable.

Output:

Dictionary keys method in Python
Dictionary keys method in Python

Example#4 Filtering dictionary keys based on a condition

Suppose we have a Python dictionary containing product names and their prices. We want to find all products with a price less than or equal to a specified value.

products = {'Laptop': 1200, 'Smartphone': 800, 'Headphones': 150, 'Monitor': 250}
max_price = 500
filtered_keys = [key for key in products.keys() if products[key] <= max_price]
print(filtered_keys)
  • In this example, we have a Python dictionary called 'products' that contains product names as keys and their prices as values.
  • We want to find all products with a price less than or equal to a specified value (in this case, 500), so we set ‘max_price’ to 500.
  • We use a Python list comprehension to iterate through the keys in the dictionary using the keys() method.
  • For each key, we check if the corresponding value (price) is less than or equal to the max_price. If the condition is met, the key is added to the 'filtered_keys' list.
  • After the list comprehension is executed, the 'filtered_keys' list will contain the product names that meet the price condition.

Output:

Dictionary keys method in Python example
Dictionary keys method in Python example

Example#5 Checking if a key exists in a dictionary using the keys() method

student_grades = {'Alice': 85, 'Bob': 78, 'Charlie': 92}
if 'David' in student_grades.keys():
      print("David's grade:", student_grades['David'])
else:
     print("David's grade not found")
  • In this example, we have a Python dictionary called 'student_grades' containing student names as keys and their grades as values.
  • We want to check if the student named 'David' exists in the dictionary. To do this, we use the keys() method in combination with the ‘in’ keyword.
  • If 'David' is present in the dictionary keys, we print his grade. Otherwise, we print a message indicating that his grade is not found.

Output:

keys method in Python Dictionary Examples
keys method in Python Dictionary Examples

Conclusion

In this article, we explored the Python dictionary keys() method using examples, which is an invaluable tool for working with dictionaries. It enables us to access and iterate through dictionary keys efficiently and can be easily converted to other data types when necessary.

You may like to read the following articles: