How does enumerate() handle dictionaries in Python?

How Does enumerate() Work with a Dictionary in Python?

I know that enumerate() is typically used for iterating over lists, but I tried it on a dictionary and it didn’t give an error.

Here is the code I used:

enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}

for i, key in enumerate(enumm):
    print(i, key)

Output:

0 0
1 1
2 2
3 4
4 5
5 6
6 7

Can someone please explain the output when using enumerate dictionary python?

I’ve worked with Python for years, and this is a common question that comes up when people explore dictionaries.

Iterating Over Dictionary Keys with enumerate() When you use enumerate() with a dictionary, it works by default on the dictionary’s keys, not on the key-value pairs. The output shows the index (i) alongside the dictionary keys because dictionaries are inherently iterable, and enumerate() assigns an index to each item in the iterable.

Here’s an example to make it clear:

enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}

for i, key in enumerate(enumm):
    print(i, key)

Output:

0 0  
1 1  
2 2  
3 4  
4 5  
5 6  
6 7  

Notice how enumerate() provides an index (i) for each key in the dictionary. This is super helpful when you need to pair keys with their position in the dictionary.

If you’re like me and love getting the most out of Python, this enhancement is great when you need both keys and values.

Using enumerate() on Dictionary Items If you want to include both the dictionary’s keys and values while still using enumerate(), you can call the .items() method. This method allows you to iterate over key-value pairs, and enumerate() will give you an index for each pair.

Here’s how it works:

enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}

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

Output:

0 0 1  
1 1 2  
2 2 3  
3 4 4  
4 5 5  
5 6 6  
6 7 7  

This approach ensures you get all the information—the index, the key, and the value. It’s an excellent way to make your loops more informative while keeping your code clean.

Here’s something I’ve often seen misunderstood, especially for Python newcomers.

Understanding enumerate() Output with Dictionary Keys By default, enumerate() iterates over the keys of a dictionary. Without explicitly calling .items(), the second variable in the loop refers to the keys, not the values. This is why your output looks like index key and not index key-value.

To sum up: When you use enumerate() with a dictionary in Python, the behavior is straightforward—

  • Without .items(), you get an index and a key.
  • With .items(), you get an index, a key, and a value.

This versatility is what makes enumerate() such a powerful tool for iterating through dictionaries. It’s simple yet incredibly useful.