DEV Community

pythonic_solutions
pythonic_solutions

Posted on

When to use enumerate( ) and dict ? More Pythonic

Image description

✅ Full Working Examples

  1. ✅ Need both index and value (enumerate())

s = "cat"
for i, ch in enumerate(s):
print(f"Index: {i}, Character: {ch}")
Output:

Index: 0, Character: c
Index: 1, Character: a
Index: 2, Character: t

  1. ✅ Track last occurrence of characters (dict)

s = "abracadabra"
last_seen = {}
for i, ch in enumerate(s):
last_seen[ch] = i
print(last_seen) # {'a': 10, 'b': 8, 'r': 9, 'c': 4, 'd': 6}

  1. ✅ Fast key-based lookup (dict)

grades = {"Alice": 95, "Bob": 87, "Charlie": 92}
print(grades["Bob"]) # 87

  1. ✅ Replacing range(len(...)) with enumerate()

numbers = [10, 20, 30]

Less Pythonic
for i in range(len(numbers)):
print(i, numbers[i])

More Pythonic
for i, num in enumerate(numbers):
print(i, num)

  1. ✅ Mapping relationships (dict)

capital = {
"France": "Paris",
"Japan": "Tokyo",
"India": "New Delhi"
}
print(capital["Japan"]) # Tokyo

Top comments (0)