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

Common Beginner Mistakes
  • Iterating Without .items(): Iterating directly over my_dict only returns the keys. To unpack both keys and values simultaneously, always use for key, value in my_dict.items():.

Quick Summary

  • Dictionary Looping: Use .items() to loop through both keys and values together.
  • Nested Dictionaries: Dictionaries inside dictionaries enable multi-level data hierarchies (users["alice"]["age"]).
  • Lists of Dictionaries: The standard Python data model for tabular rows, JSON records, and API datasets.

What's Next?

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