Iterating over dictionaries using 'for' loops

Created by sberryLinked to 88.9m issues across 53 teams

tl;dr

For Python 3.x:

To loop over both the keys and values in a dictionary, use the following syntax:

for key, value in d.items():

For Python 2.x:

To loop over both the keys and values in a dictionary, use the following syntax:

for key, value in d.iteritems():

It is important to note that key is just a variable name and can be changed to any other name. To test this, try changing the word key to test.

In Python 3.x, iteritems() was replaced with simply items(), which returns a set-like view backed by the dict, like iteritems() but even better. This is also available in 2.7 as viewitems().

The operation items() will work for both 2 and 3, but in 2 it will return a list of the dictionary's (key, value) pairs, which will not reflect changes to the dict that happen after the items() call. If you want the 2.x behavior in 3.x, you can call list(d.items()).

We use cookies to personalize content
run ads, and analyze traffic.