Start with empty braces and fill them inside the loop. To create a dictionary in Python using a for loop, assign d[key] = value on each pass, and the key is added the first time it shows up:
d = {}
for city in ["Austin", "Denver"]:
d[city] = len(city) # {'Austin': 6, 'Denver': 6}
Every output below is copied from runs on Python 3.12.5, using small US store and order data.
In this tutorial, we’ll pair two lists, count and group values, nest one loop inside another, skip rows you don’t want, and see when a comprehension is the better fit.
Create a dictionary with a for loop and square brackets
Each d[key] = value either adds a new key or replaces the value of an existing one. That’s why the repeated Denver doesn’t create a second entry:
cities = ["Austin", "Denver", "Boston", "Seattle", "Denver"]
name_length = {}
for city in cities:
name_length[city] = len(city) # new key, or overwrite an old one
print(name_length)
print(len(cities), "items in,", len(name_length), "keys out")
Output:
{'Austin': 6, 'Denver': 6, 'Boston': 6, 'Seattle': 7}
5 items in, 4 keys out

If the empty {} part is new to you, see creating an empty Python dictionary. Loop syntax itself is in the Python for loop guide.
Build a dictionary from two lists with zip() and enumerate()
When keys and values sit in separate lists, zip() hands the loop one pair at a time. enumerate() does the same with a counter, which is handy for numbered keys:
states = ["TX", "CO", "MA"]
capitals = ["Austin", "Denver", "Boston"]
capital_of = {}
for state, capital in zip(states, capitals):
capital_of[state] = capital
print(capital_of)
seat_for = {}
for seat, guest in enumerate(["Emily", "James", "Olivia"], start=1):
seat_for[seat] = guest
print(seat_for)
Output:
{'TX': 'Austin', 'CO': 'Denver', 'MA': 'Boston'}
{1: 'Emily', 2: 'James', 3: 'Olivia'}
For the one-line dict(zip(...)) version, read creating a dictionary from two lists in Python. The start argument is explained in enumerate() in Python.
Count and group values in a dictionary inside a loop
This is where a loop beats every one-liner. get(name, 0) gives a starting count, and setdefault(name, []) creates the list the first time a customer appears:
orders = [("Emily", 42.75), ("James", 18.25), ("Emily", 7.25),
("Olivia", 63.15), ("James", 12.45), ("Emily", 30.15)]
order_count, spent, amounts = {}, {}, {}
for name, amount in orders:
order_count[name] = order_count.get(name, 0) + 1
spent[name] = round(spent.get(name, 0) + amount, 2)
amounts.setdefault(name, []).append(amount)
print(order_count)
print(amounts)
for name, total in spent.items():
print(f"{name}: ${total:.2f}")
Output:
{'Emily': 3, 'James': 2, 'Olivia': 1}
{'Emily': [42.75, 7.25, 30.15], 'James': [18.25, 12.45], 'Olivia': [63.15]}
Emily: $80.15
James: $30.70
Olivia: $63.15

I wrap the running total in round(..., 2) so cents don’t drift, then print it with :.2f. Lists as values are covered in a Python dictionary of lists, and summing all values in a Python dictionary shows the totals side.
Build a nested dictionary with two for loops
Create the inner dictionary in the outer loop, then fill it in the inner loop. Forget that first line and you’ll get a KeyError on the first assignment:
stores = ["Austin", "Denver"]
months = ["Jan", "Feb", "Mar"]
units = [120, 95, 140, 80, 110, 105]
sales = {}
i = 0
for store in stores:
sales[store] = {} # inner dict per store
for month in months:
sales[store][month] = units[i]
i += 1
print(sales)
print("Denver, Feb:", sales["Denver"]["Feb"])
Output:
{'Austin': {'Jan': 120, 'Feb': 95, 'Mar': 140}, 'Denver': {'Jan': 80, 'Feb': 110, 'Mar': 105}}
Denver, Feb: 110
To read a structure like this back, iterating through a Python dictionary walks through items() and nested loops.
How do I skip items when building a dictionary in a loop?
Put an if with continue at the top of the loop. Anything that fails the check never reaches the assignment, so the dictionary only holds the rows you keep:
rows = [
{"id": "A-101", "city": "Austin", "total": 129.99, "status": "paid"},
{"id": "A-102", "city": "Boston", "total": 54.00, "status": "refunded"},
{"id": "A-103", "city": "Denver", "total": 89.95, "status": "paid"},
{"id": "A-104", "city": "Austin", "total": 15.25, "status": "pending"},
]
paid = {}
for row in rows:
if row["status"] != "paid":
continue # skip it, nothing is added
paid[row["id"]] = {"city": row["city"], "total": row["total"]}
print(paid)
print(f"Paid total: ${sum(p['total'] for p in paid.values()):.2f}")
Output:
{'A-101': {'city': 'Austin', 'total': 129.99}, 'A-103': {'city': 'Denver', 'total': 89.95}}
Paid total: $219.94

Keying by a unique ID like the order number is the safe choice. Key by city instead, and two paid orders from the same city would overwrite each other.
For loop vs dictionary comprehension: which should you use?
Both give the same dictionary. The comprehension is shorter; the loop has room for counters, try blocks and print statements while you debug:
prices = {"coffee": 3.50, "bagel": 2.25, "muffin": 3.00}
with_tax = {}
for item, price in prices.items():
with_tax[item] = round(price * 1.0825, 2)
same = {item: round(price * 1.0825, 2) for item, price in prices.items()}
print(with_tax)
print("Same result:", with_tax == same)
Output:
{'coffee': 3.79, 'bagel': 2.44, 'muffin': 3.25}
Same result: True
My rule: one expression per key, use a comprehension; anything more, keep the loop. The full syntax is in Python dictionary comprehension.
Want more practice with dictionaries? These four pick up where this one stops:
- Create a dictionary from a list in Python
- Count the keys in a Python dictionary
- Update values in a Python dictionary
- Filter a Python dictionary
Frequently asked questions
How do you create a dictionary in Python using a for loop?
Make an empty dict with d = {}, then assign d[key] = value inside the loop.
Can a for loop add duplicate keys to a dictionary?
No. Keys are unique, so a repeated key overwrites the earlier value.
How do I loop over two lists to build a dictionary?
Use for k, v in zip(keys, values): d[k] = v. It stops at the shorter list.
How do I count items with a for loop and a dictionary?
Write counts[item] = counts.get(item, 0) + 1 on each pass.
Is a dictionary comprehension faster than a for loop?
Usually a little, but pick the one that reads better. Use a loop when each item needs several steps.
Where are Python dictionaries documented?
See Dictionaries in the Python tutorial.

Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn