Python 3 – dictionary keys() Method
In Python programming, the dictionary keys() method returns a view object consisting of the keys of the specified dictionary. The keys() method returns a list of all the keys in a dictionary that can be used for various purposes like iteration, sorting, etc.
Here is the syntax of the dictionary keys() method:
dict.keys()
Example
Let’s take an example to illustrate the use of dictionary keys() method. Below is a simple program that demonstrates how to use the keys() method:
# Create a dictionary
myDict = {1: 'apple', 2: 'banana', 3: 'cherry'}
# Get all the keys in the dictionary
keys = myDict.keys()
# Print the keys
print(keys)
Output:
dict_keys([1, 2, 3])
How it works
As we can see in the above example, we first create a dictionary myDict
that contains three key-value pairs. Next, we use the keys()
method to get all the keys from the dictionary. The keys()
method returns a dict_keys
object that contains all the keys of the dictionary.
Using keys() with for loop
One of the most common uses of the keys()
method is to iterate over the keys of a dictionary using a for
loop. Here is an example:
# Create a dictionary
fruits = {'apple': 2, 'banana': 3, 'cherry': 5}
# Iterate over the keys of the dictionary using a for loop
for key in fruits.keys():
print(key)
Output:
apple
banana
cherry
In the above example, we first create a dictionary fruits
that contains three key-value pairs. Next, we use a for
loop to iterate over the keys of the dictionary using the keys()
method. The for
loop assigns each key to the variable key
and then prints it out.
Using keys() with list()
Another use of the keys()
method is to convert the keys of a dictionary to a list. Here is an example:
# Create a dictionary
myDict = {1: 'apple', 2: 'banana', 3: 'cherry'}
# Get all the keys in the dictionary as a list
keys = list(myDict.keys())
# Print the keys
print(keys)
Output:
[1, 2, 3]
In the above example, we first create a dictionary myDict
that contains three key-value pairs. Next, we use the keys()
method to get all the keys from the dictionary and then convert the dict_keys
object into a list using the list()
method. Finally, we print the list of keys.
Conclusion
In conclusion, the keys()
method is a powerful method in Python that can be used for various purposes like iteration, sorting, etc. It returns a view object consisting of the keys of a dictionary that can be manipulated using various Python methods. Python programmers can use this method to make their code more efficient and effective.