Python Dictionary – Loop through Keys

Python Dictionary – Loop through Keys

A dictionary is a collection of key:value pairs. You may need to access and loop through only the keys of the dictionary.

To access the keys alone of a Python Dictionary, use the iterator returned by dict.keys(). Then use Python For Loop to iterate through those keys.

Examples

1. Loop through Dictionary Keys using dict.keys()

In this example, we will initialize a dictionary with some key:value pairs, and use for loop to iterate through keys in the dictionary.

Python Program

dictionary = {'a': 1, 'b': 2, 'c':3}

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

Output

a
b
c

2. Loop through Dictionary Keys using dict.items()

Similar to dict.keys(), dict.items() returns both key,value during each iteration. You can access only the key from the key:value, while traversing through the dictionary.

Python Program

dictionary = {'a': 1, 'b': 2, 'c':3}

for key, value in dictionary.items():
    print(key)
Run Code Copy

Output

a
b
c

Summary

In this tutorial of Python Examples, we learned how to iterate through keys of a Dictionary with the help of well detailed examples.

Code copied to clipboard successfully 👍