Multiple ways to iterate over Dictionary using for loops in Python

There are multiple for loops in Python to iterate the Key and values of the dictionary.

Dictionary in Python contains key and value pairs. Dictionaries are created with and initialized with braces ({}) and pairs of objects are separated by commas.

emp = {'id': 1, 'name': 'john', 'salary': 3000}

For loop in python provides iteration to iterate key and values.

This tutorial explains about

  • How to unpack key and value pairs
  • Iterate through each key and values
  • Loop over dictionary object
  • Loop over tuple of key, value pair in dictionary

Multiple ways to iterate dictionary with for loops

There are multiple ways to iterate and loop keys and values in Dictionaries

In All the below approaches, the Key and value pair iterated in insertion order.

First#1 - Iterate keys and print keys and values

Here is a for-loop syntax for dictionary key iteration

for  key in dictionary:
{
    //key - get key
    //dictionary[key] - value
}

key contains each iterated object key value can be retrieved using the dictionary[key] syntax

Here is an example

emp = {'id': 1, 'name': 'john', 'salary': 3000}

for key in emp:
    print(key, ' - ', emp[key])

Output:

id  -  1
name  -  john
salary  -  3000
  • Second# To iterate keys only in the dictionary dictionary.keys() method returns a list of keys that can be iterated in for loop as given below in Python 3.x.

dictionary.iterkeys() can be used in python 2.x .

for key in emp.keys():
    print(key, ' - ', emp[key])

Output:

id
name
salary
  • #Third To iterate values only in the dictionary. The dictionary.values() method returns a list of values that can be iterated in for loop as given below in Python 3.x.

dictionary.itervalues() can be used in python 2.x .

for key in emp. values():
    print(key)

Output:

1
john
3000
  • #Four To iterate key and value pair in for loop in the dictionary

    • Python 3.x: dictionary.items() method returns list of objects(key and value pair) which can be iterated in for loop
    • Python 2.x : dictionary.iteritems() method returns list of objects(key and value pair) which can be iterated in for loop
for key,value in emp. items():
    print(key , " - ", value)

Output:

id  -  1
name  -  john
salary  -  3000

Iterate dictionary with index, key, and value pair in Python

This example uses to print the index and key, value pair.

  • dictionary.items return the list of key and value pairs.
  • pass this list to enumerate and use in for loop
  • It iterates and returns index and object pair separated by a comma
  • Finally, Print the index, key, and value pair
for index, (key, value) in enumerate(emp.items()):
   print(index, key, value)

Output:

0 id 1
1 name john
2 salary 3000