How to Iterate Over Dictionaries Using For Loops

Python Dictionaries allow you to store large amounts of data in a compact manner. Software developers heavily rely on dictionaries to store data in key-value format. Often they need to loop over dictionaries to access their keys, values or both keys & values. This is commonly required to access, modify, filter or manipulate data. There are several ways to loop over Python dictionaries. In this article, we will learn the most popular and powerful ways to iterate over dictionaries.

How to Iterate Over Dictionaries Using For Loops

Here are the different ways to iterate over Python dictionaries. Let us say you have the following Python dictionary.

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

1. Iterate Over Keys Only

Since every dictionary item consists of key-value pairs, you can iterate over keys only, values only or both keys and values. In this case, you iterate over the keys of your dictionary only. This is the default way to iterate over a dictionary using for loop. For example, when you use the following code, Python will use the key values in each iteration.

for i in data:
print i

Here is the output

a
b
c

When you run for loop over dictionary this way, it automatically executes the .__iter__() builtin function available for each dictionary.

This is very convenient since you can use the key to get the value in each iteration, as shown.

for i in data:
print data[i]

Here is the output.

1
2
3

You can also use this approach to get both key as well as value in each iteration.

for i in data:
print(i, data[i])

Here is the output.

a 1
b 2
c 3

Python also provides several ready made methods that directly return a list of all keys in dictionary. You can loop through this list to iterate over the keys. keys() is one such function. Here is an example of a list of keys of dictionary data, where each item of list is a string.

>>> data.keys()
['a', 'b', 'c']

Here is an example to iterate over this list of dictionary keys.

for i in data.keys():
print i

Here is the output.

'a'
'b'
'c'

If you have a very large dictionary with many keys, you can use iterkeys() function which returns an iterator to the list of keys, instead of returning an entire list of keys that is loaded into the system memory. You can iterate over dictionary keys using this iterator.

for i in data.iterkeys():
print i

Here is the output.

'a'
'b'
'c'

Please note, iterkeys() function may not be available in older Python versions such as Python <=2.

2. Iterate Over Values Only

On the other hand, if you want to access only the values of dictionary, or you want to loop over only the values of Python dictionary, then you can use functions such as values() and itervalues() for this purpose. They are built-in functions available by default for every dictionary.

>>> data.values()
[1, 2, 3]

>>> data.itervalues()
<dictionary-valueiterator object at 0x0333F750>

You can loop through either of them to get all dictionary values. Here is an example to loop through the result returned by values() function.

>>> for i in data.values():
print i
1
2
3

Here is an example to use itervalues().

>>> for i in data.itervalues():
print i
1
2
3

The main difference between using values() and itervalues() is that values() function returns a list of all dictionary values whereas itervalues() returns an iterator to the list of values. Since iterators do not occupy much memory, it is very useful if you have a large dictionary with many key-value pairs. On the other hand, the list returned by values() will be loaded into memory. So, itervalues() function offers better performance than values() function.

In the previous method, we saw that if you have the key of each item in each iteration, you can easily get its value also. But in this case, if you have the value, you cannot retrieve the key.

Please note, itervalues() function may not be available in older Python versions such as Python 2.

3. Iterate Over Keys & Values

Sometimes, you may need to iterate over both key as well as values in a Python dictionary. For this purpose, you can use items() or iteritems() function. items() function will return a list of tuples, where each tuple consists of key and value as 2 items of the tuple. iteritems() returns an iterator to the list of such tuples. Every time you access the iterator, it will return a tuple consisting of key and value of next item in dictionary. Both these functions are available by default for every dictionary.

>>> data.items()
[('a', 1), ('c', 3), ('b', 2)]

>>> data.iteritems()
<dictionary-itemiterator object at 0x0333F750>

You can loop through this list to get key-value combinations in each iteration.

for i, j in data.items():
print i, j

Here is the output.

a 1
b 2
c 3

Here is an example to loop through keys and values using iteritems().

>>> for i, j in data.iteritems():
print i, j
a 1
b 2
c 3

Here again the key difference between iteritems() and items() is that iteritems() returns an iterator to a dictionary, which is memory efficient whereas items() returns list of tuples which is completely loaded into memory.

4. Iterate over Sorted Keys

So far we have seen how to iterate though dictionary in whatever order the items are present. In Python <=3.6, dictionary items are stored in no particular order whereas in Python >=3.7, they are stored in the same order as they are inserted. Nevertheless, sometimes Python developers need to iterate over the dictionary items in sorted order. You can do this by calling sorted() function on the dictionary.

When you call sorted() function on an iterable such as dictionary, it will return a sorted list of dictionary keys.

>>> sorted(data)
['a', 'b', 'c']

You can iterate over this list to get a sorted order of keys. In each iteration, you can use these keys to get their corresponding values too.

>>> for i in sorted(data):
print i, data[i]

a 1
b 2
c 3

Please note, in this case, we have directly called sorted() function on the dictionary instead of its keys. If you called sorted on its list of keys, still you will get the same result.

>>> for i in sorted(data.keys()):
print i, data[i]
a 1
b 2
c 3

On the other hand, if you pass a list of dictionary values to sorted() function, using data.values(), then sorted() function will return a list of sorted values. You can iterate over this list to loop over sorted values.

>>> for i in sorted(data.values()):
print i
1
2
3

Sometimes, you may want to iterate through the sorted list of values, and get its key as well as value in each iteration. In this case, we will need to use the key argument of sorted function to specify that the sort key is value. We do this by creating a lambda function which simply returns the value of each tuple.

>>> for i, j in sorted(data.items(),key=lambda item:item[1]):
print i, j

a 1
b 2
c 3

In other words, the lambda function tells sorted() function to sort result of data.items() by second item of each tuple, that is item[1].

This is a very simple way to control the order of iteration of dictionary items.

5. Iterate in Reverse Order

On the other hand, sometimes you may need to traverse the items in reverse order. In this case, you need to use reverse=true argument in sorted function. Again, here also you can choose to sort keys or values, depending on your requirement. We will look at each of these cases one by one. Here is an example to reverse sort and iterate through the keys of a dictionary.

>>> for i in sorted(data,reverse=True):
print i

c
b
a

Here is an example to not only reverse sort dictionary keys but also access the keys and corresponding values in each iteration.

>>> for i in sorted(data,reverse=True):
print i, data[i]

c 3
b 2
a 1

If you only want to reverse sort and iterate through the dictionary values then you can pass data.values() in sorted function.

>>> for i in sorted(data.values(),reverse=True):
print i

3
2
1

Sometimes, you may want to reverse sort a dictionary’s values, and display both keys and values together, in each iteration. In this case, you pass data.items() to sorted function. data.items() returns a list of 2-item tuples where each tuple consists of key and value. We also set reverse=True to reverse sort the list of values. Lastly, we define key argument with a lambda function, where we specify the key to be the second item of tuple, that is, item[1].

>>> for i, j in sorted(data.items(),reverse=True,key=lambda item:item[1]):
print i, j

c 3
b 2
a 1

This approach is useful if the original order of key-value pairs is not as per your requirement and you want to change it as per your requirement.

6. Iterate over Multiple dictionaries

Sometimes, software developers need to loop over multiple dictionaries at the same time. There are several ways to do this in Python. In this article, we will learn how to do this one by one.

Let us say you have two dictionaries.

data = {'a':1,'b':2,'c':3}
data2 = {'d':4,'e':5,'f':6}

You can easily merge these two dictionaries and iterate through the merged result using unpacking operator(**). In case these dictionaries have duplicate keys, the value of the rightmost dictionary will overwrite other values. Here is an example to easily iterate over multiple dictionaries data and data2. We need to mention dictionaries in curly braces {} in a comma-separated manner. Each of these dictionaries should be prefixed by unpacking operator. Then the entire list of dictionaries within curly braces can be treated as a single dictionary.

for i,j in {**data, **data2}.items():
print(i, "->", j)

Here is the output.

a -> 1
b -> 2
c -> 3
d -> 4
e -> 5
f -> 6

Please note, in this case, the original dictionaries remain unchanged.

Python also provides a couple of other functions for this purpose. First one is a special container called ChainMap. It allows you to create a single dictionary like object that spans across multiple dictionaries. It can be accessed and used as a single dictionary. Here is an example to use a ChainMap constructor to create a unified view of data and data2 dictionaries.

from collections import ChainMap
data3 = ChainMap(data, data2)

for i, j in data3.items():
print(i,'->',j)

In the above code, we first import ChainMap object from collections. We use it to create a unified view of dictionaries data and data2. We loop through the items of this dictionary to display key and values. Here is the output.

d -> 4
e -> 5
f -> 6
a -> 1
b -> 2
c -> 3

Again, please note, this does not alter the original dictionaries in any way.

You can also use chain() function from itertools library for this purpose. It accepts multiple iterables such as dictionaries, as arguments, and returns an iterator that yields all elements from all of the individual iterables. Every time chain() function is accessed, it returns the next element of the iterable, until all elements are exhausted.

from itertools import chain
data3 = chain(data.items(), data2.items())

for i, j in data3:
print(i,'->',j)

In the above code, we pass data.items() and data2.items() to chain() function to get an iterator that can loop through all elements of both dictionaries. In each iteration of for loop, we print the key and values together.

Here also, the original dictionaries remain unchanged.

This is a very useful feature in Python. Otherwise, it would have become very tedious to loop through multiple dictionaries.

7. Using map() function

Sometimes, we may need to not only loop through all elements of a dictionary but also apply a specific function to each element. For this purpose, we can use map() function. It takes a function object along with an iterable and applies the function to each element of the iterable. Here is an example to illustrate it.

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

def double(item):
return item[0],2*item[1]

print(dict(map(double, data.items())))

In the above code, we first define a dictionary data. We then define a simple python function that takes in a key-value pair, and returns the key along with the 2 x value. We call map() function with two arguments – the double function and the items of data dictionary. We pass the result of map() function, that is, a map object to dict() constructor to convert it into a dictionary. Here is the output. You will see that each value of dictionary has been doubled. This is because the double() function looped through the dictionary and doubled each key-value pair’s value.

{'a': 2, 'b': 4, 'c': 6}

8. Using filter() function

Sometimes, you may need to loop through a dictionary and filter certain items from it, using one or more conditions. For this purpose, you can use filter() function. It also takes an iterator and a function object as arguments, and returns an iterator to those elements from original dictionary that satisfy the filter condition.

As in the case of map() function, we will first define a simple Python function that checks if an item is odd or not using modulus (%) operator, and use it with filter() function as shown below.

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

def check(item):
return item[1]%2==1

print(dict(filter(check, data.items())))

In the above code, we pass function object of check() along with the items of data dictionary to filter() function. The filter function will iterate over each key-value pair of data dictionary and check whether the value of each item is odd or not. Those items that pass the condition are returned. So you get a dictionary where each item value is an odd number. Here is the output.

{'a': 1, 'c': 3}

Conclusion

In this article, we have learnt several important ways to iterate over dictionaries using for loops. We learnt how to loop over keys only, values only and a combination of keys and values, in a dictionary. We have also learnt different ways to iterate over multiple dictionaries at the same time. Then we learnt how to iterate over a dictionary and execute specific function for each item, using map() function. Lastly, we learnt how to iterate over dictionary and filter its items for one or more conditions using filter() function. You can use any of these solutions as per your requirement.

FAQ

1. How to iterate over keys in Python dictionary?

You can use keys() function available for each dictionary to get a list of dictionary keys. You can easily loop over this list. Alternatively, you can directly iterate over the dictionary. It will return the key value.

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

for i in data:
print i

2. How to iterate over values in Python dictionary?

Use the above method to get keys of your dictionary. While looping through the keys, use the key to get value.

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

for i in data:
print data[i]

3. How to iterate over both keys and values in dictionary?

As shown above, in each iteration, you will have access to both key as well as value. You can use them to iterate over both key and values in dictionary.

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

for i in data:
print(i, data[i])

4. How to iterate through dictionary in reverse order?

You can call sorted() function, with your dictionary as one of the argument, and reverse=True as the other argument. This will reverse sort the dictionary and allow you to iterate the dictionary in reverse order.

>>> data = {'a':1, 'b':2, 'c':3}
>>> for i in sorted(data, reverse=True):
print i, data[i]

c 3
b 2
a 1

5. How to iterate through multiple dictionaries?

You can iterate through multiple dictionaries using unpacking operator, map() function or filter() function.

Also read:

How to Find Given Item in Python List
How to Flatten List of Lists in Python
How to Access Index Value in Python

Leave a Reply

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