In this article we will discuss different ways to iterate over a dictionary

Suppose we have a dictionary with string as key and integers as value i.e.

Now let’s see how to iterate over this dictionary using 2 different techniques i.e.

Iterate over the dictionary using for loop over keys | “for in dictionary”

By using for in dictionary, it loops through all the keys in dictionary and for each key select the value and prints it.


Its not an efficient solution because we are iterating over all the keys in dictionary and for each key we are again searching for its associated value.

Let’s see an efficient method i.e.

Iterate over key value pairs of dictionary using dict.items()

It returns a iterable View object of all key,value elements in the dictionary. Its backed by original dictionary.

Let’s iterate over the list using dict.iter() i.e.


As, view object is backed by original dictionary, therefore any changes made in dictionary will be reflected in it.
For example,

Take a view object of dictionary i.e.

View object is,

Now modify the dictionary

Now same view object will also be modified because its backed by original dictionary

Top 5 online Python courses for beginners in 2019- 2020

Complete example is as follows,



Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.