Python Dict for Loop With Index

Apr 24, 2019

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)

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.