Python – Print Dictionary Keys

Python – Print dictionary keys

To print the keys in a Python Dictionary,

  1. Given a dictionary object my_dict.
  2. Call keys() method on the given dictionary object. The keys() method returns an iterator over the keys.
  3. Now, you can convert this keys iterator into a list and print the list of keys, or use a For loop to iterate over the keys and print each of the key individually.
  4. If you choose to print the keys as a list, pass the keys iterator object as argument to the list() built-in function, and print the returned list to output. The task is completed.
  5. Or, if you choose to print the keys individually, write a For loop with the keys iterator. We iterate through the keys in the dictionary.
  6. For each key inside the loop, print the key. The task is completed.

Examples

1. Printing the keys in given dictionary as a list in Python

We are given a Python dictionary in my_dict. We have to print the keys of this dictionary.

We shall get the iterator to keys in the dictionary using my_dict.keys(), and pass the keys iterator as argument to the list(). We will get the keys in the dictionary as a list. Then we shall print this list of keys to output using print() function.

Python Program

my_dict = {
    'apple': 10,
    'banana': 20,
    'cherry':30
}

keys = list(my_dict.keys())
print(keys)
Run Code Copy

Output

['apple', 'banana', 'cherry']

2. Printing keys in the dictionary to output one by one using For loop

We are given a Python dictionary in my_dict. We have to print the keys of this dictionary one by one using a For loop.

We shall get the iterator for the keys in the dictionary using my_dict.keys(), and use this keys iterator object in a For loop. Inside the For loop, we shall print each key to the output using print().

Python Program

my_dict = {
    'apple': 10,
    'banana': 20,
    'cherry':30
}

for key in my_dict.keys():
    print(key)
Run Code Copy

Output

apple
banana
cherry

Summary

In this tutorial of Python Examples, we learned how to print the dictionary keys as a list or one by one, with the help of well detailed examples.

Related Tutorials

Code copied to clipboard successfully 👍