Python: Loop / Iterate over all keys of Dictionary

In this article, we will discuss different ways to iterate over all keys of a python dictionary.

Table of Contents

Loop over all keys of dictionary using for loop

A dictionary object can also be used as an iterable object, to iterate over the keys of dictionary. If we use it with a for loop then we can easily iterate over all keys of the dictionary. For example,

# Dictionary of string and integers
word_freq = {
    'Hello' : 56,
    'at'    : 23,
    'test'  : 43,
    'This'  : 78,
    'Why'   : 11
}

# Iterate over all keys of dictionary
for key in word_freq:
    print(key)

Output:

Hello
at
test
This
Why

Here, we used the dictionary object as an iterator and iterated over all keys of the dictionary to printed them one by one.

Loop over all keys of dictionary using keys()

In previous example, we used the concept that dictionary can be used as an iterator. Sometimes people gets confused by looking into that type of code. So, let’s look at a more clear solution.

In python, dictionary class provides a function keys(), it returns an iterable sequence of all keys of the dictionary i.e. dict_keys. It is a view of all keys of the dictionary, it means any change in original dictionary will be reflected in this sequence. Also, we can not use indexing with this sequence. But we can use this along with a for loop to iterate over all keys of the dictionary. For example,

# Dictionary of string and integers
word_freq = {
    'Hello' : 56,
    'at'    : 23,
    'test'  : 43,
    'This'  : 78,
    'Why'   : 11
}

# Iterate over all keys of dictionary
for key in word_freq.keys():
    print(key)

Output:

Hello
at
test
This
Why

We iterated over all keys of dictionary and printed them line by line.

Loop over all keys of dictionary using items()

In python, dictionary class provides a function items(), it returns an iterable sequence of all key-value pairs of the dictionary i.e. dict_items. It is a view of all items (key-value pairs) of the dictionary, it means any change in original dictionary will be reflected in this sequence. Also, we can not use indexing with this sequence. We can use this along with a for loop to iterate over all pairs of the dictionary and while iteration we can select the first element of pair / tuple i.e. is the key. For example,

# Dictionary of string and integers
word_freq = {
    'Hello' : 56,
    'at'    : 23,
    'test'  : 43,
    'This'  : 78,
    'Why'   : 11
}

# Iterate over all keys of dictionary
for key, value in word_freq.items():
    print(key)

Output:

Hello
at
test
This
Why

We iterated over all keys of dictionary and printed them line by line.

Summary:

We learned about different ways to iterate over all keys of a dictionary in python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top