How to iterate over a dictionary

Use items() to get an iterable of (key, value) pairs from test:

for fruit, color in test.items():
    # do stuff

This is covered in the tutorial.

In Python 2, items returns a concrete list of such pairs; you could have used iteritems to get the same lazy iterable instead.

for fruit, color in test.iteritems():
    # do stuff

Leave a Comment