In Python, you can print the keys of a dictionary by using the keys()
method. This method returns a view object that displays a list of all the dictionary’s keys.
Here’s how you can print the keys of a dictionary:
Example 1: Print all keys of a dictionary
my_dict = {"apple": 1, "banana": 2, "cherry": 3}
# Print all keys
print(my_dict.keys())
Output:
dict_keys(['apple', 'banana', 'cherry'])
The keys()
method returns a view object of the dictionary’s keys. If you want to print the keys individually, you can loop through them.
Example 2: Loop through and print each key
my_dict = {"apple": 1, "banana": 2, "cherry": 3}
# Loop through the dictionary and print each key
for key in my_dict:
print(key)
Output:
apple
banana
cherry
Example 3: Print keys as a list
If you want to print the keys as a regular list (not as a view object), you can convert the dict_keys
view to a list:
my_dict = {"apple": 1, "banana": 2, "cherry": 3}
# Convert dict_keys to a list and print
print(list(my_dict.keys()))
Output:
['apple', 'banana', 'cherry']