Monday, January 20, 2025
HomeProgrammingPython - How To Print A Dictionary's Key?

Python – How To Print A Dictionary’s Key?

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.

See also  What is the java.util package in Java?

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']

 

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x