First page Back Continue Last page Overview Graphics

Iterate through a Dictionary

Python 2:

Iterating over the keys of a Dictionary:

for key in d:

print(key)

This is equivalent to:

for key in d.iterkeys():

print(key)

Attention: The keys method creates a list and not an Iterator (itemview) like iterkeys():

for key in d.keys():

print(key)

It's possible to iterate over the values with itervalues() :

for val in d.itervalues():

print(val)

Python 3:

Iterating over the keys of a Dictionary:

for key in d:

print(key)

The method iterkeys()doesn't exist anymore in Python 3.

keys() behaves like iterkeys()of Python 2.

It's possible to iterate over the values with values() :

for val in d.values():

print(val)