Ravindra BagaleCourses & study guides मराठी Track your progress

Python for Loops and while Loops Explained with Examples (range, break, continue)

P6.3 Loop Over Dictionaries and Use enumerate in Python

Why. Prices by item, stock by warehouse — dictionary data needs looping too. And often you need a row number.

What. for k, v in d.items(): gives each key and value. for i, x in enumerate(list, 1): gives a counter and the item.

How.

Loop with two names

  1. Pick the right helper: .items() or enumerate().
  2. Write two names before in.
  3. Use both inside the block.

Worked example A — Stock by warehouse.

Step 1 — What we do. A logistics company has stock in three warehouses.

Step 2 — Type and run this code.

stock = {"Mumbai": 320, "Delhi": 150, "Chennai": 45}
for city, units in stock.items():
    print(city, units)

Step 3 — Output you should see.

Mumbai 320
Delhi 150
Chennai 45

Step 4 — What it means. Each loop gives one key (city) and its value (units).

Worked example B — Numbered list with enumerate.

Step 1 — What we do. We print a numbered top list of products.

Step 2 — Type and run this code.

products = ["Laptop", "Monitor", "Mouse"]
for i, p in enumerate(products, 1):
    print(f"{i}. {p}")

Step 3 — Output you should see.

1. Laptop
2. Monitor
3. Mouse

Step 4 — What it means. enumerate(..., 1) counts from 1. No manual counter needed.

Worked example C — Find low stock.

Step 1 — What we do. We flag warehouses with less than 100 units.

Step 2 — Type and run this code.

stock = {"Mumbai": 320, "Delhi": 150, "Chennai": 45}
for city, units in stock.items():
    if units < 100:
        print(f"Reorder for {city}: only {units} left")

Step 3 — Output you should see.

Reorder for Chennai: only 45 left

Step 4 — What it means. Loop plus if = a simple alert system.

Ravindra Bagale's Tip

Use enumerate instead of range(len(list)). It is shorter and avoids index mistakes.