Skip to main content

Looping Through Dictionaries

When you want to inspect or display dictionary records, you can loop over the keys, the values, or both simultaneously using .items().

Looping Over Keys and Values (.items())

The cleanest way to loop through a dictionary is looping over .items(), which unpacks each pair into two variables:

scores = {"Alice": 95, "Bob": 88, "Charlie": 92}

for student, score in scores.items():
print(f"{student} scored {score} marks.")

Looping Over Keys Only

By default, looping directly over a dictionary iterates through its keys:

user = {"name": "Alice", "country": "India"}

for key in user:
print(f"Key label: {key}")

Nested Dictionaries (Complex Data)

In real software and web APIs, data is often nested: a dictionary can contain lists, and can even contain other smaller dictionaries inside!

# A dictionary where values are lists and sub-dictionaries
company = {
"name": "Think IT Telugu Tech",
"employees": ["Alice", "Bob", "Charlie"],
"headquarters": {
"city": "Hyderabad",
"pin": 500081
}
}

# Accessing an item inside the nested list
first_employee = company["employees"][0]
print(first_employee) # Output: Alice

# Accessing the nested city value
city_name = company["headquarters"]["city"]
print(city_name) # Output: Hyderabad

Common Beginner Mistakes

Looping over a dictionary without .items() when needing both key and value
# Wrong - looping over dictionary directly only yields keys
scores = {"Alice": 95}
for item in scores:
print(item) # Only prints "Alice", not 95!

# Right - use .items() to get both variables
for name, score in scores.items():
print(f"{name}: {score}")

What's Next?

Congratulations on mastering dictionaries! Let's move to Module 12: Functions to learn how to write reusable blocks of logic using def.