Iterating over dictionaries

suggest change

Considering the following dictionary:

d = {"a": 1, "b": 2, "c": 3}

To iterate through its keys, you can use:

for key in d:
    print(key)

Output:

"a"
"b"
"c"

This is equivalent to:

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

or in Python 2:

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

To iterate through its values, use:

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

Output:

1
2
3

To iterate through its keys and values, use:

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

Output:

a :: 1
b :: 2
c :: 3

Note that in Python 2, .keys(), .values() and .items() return a list object. If you simply need to iterate trough the result, you can use the equivalent .iterkeys(), .itervalues() and .iteritems().

The difference between .keys() and .iterkeys(), .values() and .itervalues(), .items() and .iteritems() is that the iter* methods are generators. Thus, the elements within the dictionary are yielded one by one as they are evaluated. When a list object is returned, all of the elements are packed into a list and then returned for further evaluation.

Note also that in Python 3, Order of items printed in the above manner does not follow any order.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents