DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk2 min

How to Iterate Through a Python Dictionary with an Index

Use enumerate(d.items()) to loop through dictionary entries with a counter, while keeping clear that the counter is not a dictionary key.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use enumerate() with dict.items() to loop through a dictionary while keeping a position counter:

scores = {"Ada": 91, "Linus": 87, "Grace": 95}

for i, (name, score) in enumerate(scores.items()):
    print(i, name, score)

The counter starts at 0. It marks the entry’s position during iteration; it is not necessarily a key in scores.

Choose the loop based on what you need

Iterating over a dictionary directly produces its keys. Use .values() for values, .items() for key-value pairs, or enumerate() to add a separate counter.

What you need Loop
Keys only for key in d:
Values only for value in d.values():
Keys and values for key, value in d.items():
Counter, keys, and values for i, (key, value) in enumerate(d.items()):
Counter and keys only for i, key in enumerate(d):

The Python tutorial documents retrieving each key and its corresponding value with items(). The built-in enumerate() adds a counter to each item from an iterable.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use the counter for display, not as a key

A dictionary is a mapping, not a sequence indexed by position. In for i, (key, value) in enumerate(d.items()), i is generated by enumerate(), while key is the dictionary key. To retrieve the value, use d[key] rather than assuming d[i] refers to the entry at position i.

For a one-based counter, pass a starting value:

for i, (key, value) in enumerate(d.items(), start=1):
    print(i, key, value)

This changes the counter, not the dictionary’s keys. The official documentation describes the start argument as the value from which enumeration begins.

What determines dictionary iteration order?

In Python 3.7 and later, insertion order is guaranteed by the language: keys are produced in the order they were added. Replacing the value for an existing key does not change its position. Removing a key and inserting it again moves it to the end. CPython 3.6 also preserved insertion order, but only as an implementation detail, not a language guarantee. See the Python data model documentation.

Insertion order is not sorted order. If you specifically want keys in sorted order, iterate over sorted(d):

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
for i, key in enumerate(sorted(d)):
    print(i, key, d[key])

This sorts the keys for the loop; it does not reorder the dictionary itself. The Python tutorial includes examples of sorting dictionary keys.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Select an entry by numeric position

d[0] looks up the key 0; it does not mean “the first entry.” If you need to select an entry by position, convert the entries to a list first:

entry = list(d.items())[i]
key, value = entry

For keys alone, list(d)[i] returns the key at that position in iteration order. These conversions create lists, so if your goal is simply to visit entries, iterate over the dictionary directly instead.

Avoid common indexing and unpacking errors

  • Using the counter as a key: d[i] works only if i is an actual key. Use the key yielded by the loop to access its value.
  • Unpacking the result of items() incorrectly: enumerate(d.items()) yields a counter and a key-value pair. Unpack it as for i, (key, value) in ....
  • Expecting a missing key to behave like a position: d[key] raises KeyError if that key is absent. Use d.get(key, default) when you want a fallback value, as shown in the Python tutorial.
  • Assuming insertion order in older Python versions: the language-level guarantee begins with Python 3.7; CPython 3.6’s ordering behavior was implementation-specific.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.