Iterate Over a Dictionary in Python

1 min read

Iterate keys and values

Python 3.x

To iterate over the key and value for each item in a Python 3 dictionary you can use the dictionary's items() method:

d = {'name': 'Jordan', 'surname': 'Francis'}

for key, value in d.items():
    print(key, value)

# name Jordan
# surname Francis

Python 2.x

To iterate over the key and value for each item in a Python 2 dictionary you can use the dictionary's iteritems() method:

d = {'name': 'Jordan', 'surname': 'Francis'} for key, value in d.iteritems(): print key, value # surname Francis

# name Jordan

The words key and value above are used to assign reference names to the key and and value of each iteration within the for loop block of code. You can use whatever two words you like so long as you remember that they key will always be assigned to the first word and the value to the second word. The two words also need to be separated by a comma. A common convention is to abbreviate these words to k and v for simple loops. However, if your for loop starts to become complex using short names like this may affect the readability of your code, so don't make things too concise at the expense of readability.

Ordering

Dictionaries in Python cannot store items in any particular order. If you'd like to order your results then you can read How to Sort a Python Dictionary by Keys or Values to see how it's possible to manipulate the order of the output when iterating over a Python dictionary.

The comma used to separate the variables in the print statements above is shorthand for printing two variables with a space between them. If you'd like greater control over how variables are printed you can read up about Python string formatting.

Iterate keys only

To iterate over a dictionary's keys only, you can use the keys() method in both Python 2 and Python 3:

d = {'name': 'Jordan', 'surname': 'Francis'}

for key in d.keys():
   print(key)

# name
# surname

Iterate values only

To iterate over a dictionary's values only, you can use the values() method in both Python 2 and Python 3:

d = {'name': 'Jordan', 'surname': 'Francis'}

for value in d.values():
    print(value)

# Jordan
# Francis



Author picture
Rhett Trickett

Founder at Able

@rhett RhettTrickett rhetttrickett
Python

Join the discussion

Able is a developer community where people build their coding knowledge and careers.

Join with GitHub Join with Twitter