Python Dict for Loop With Index

March 28, 2020

Python 2.x

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

NOTE: dict.items() exist in Python 2.x as well, but it return a copy of the dictionary’s list of (key, value) pairs, thus not good for performance/memory. dict.iteritems() return an iterator.

for key in items:
    value = items[key]

NOTE: The above works as well, but using iteritems should offer slightly better performance as no lookup is required.

If you need to mutate the dict while looping:

for key in items.keys():
    if key > 10:
        del items[key]

Python 3.x

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

With Index

for index, (key, value) in enumerate(items.items()):
    print(index, key, value)

NOTE: dict.items() return a new view of the dictionary’s items ((key, value) pairs)

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.