🧾 Python Dictionaries
Estimated reading: 3 minutes 30 views

πŸ” Python Loop Dictionaries: keys(), values(), items()

🧲 Introduction – Why Loop Through Dictionaries?

Dictionaries are unordered key-value stores, and one of the most common tasks is to iterate through them to process data, display values, or perform conditional operations.

Python provides elegant looping mechanisms using .keys(), .values(), and .items() to access keys, values, or both at once.

🎯 In this guide, you’ll learn:

  • How to loop through dictionary keys, values, and items
  • Real-world use cases for each iteration style
  • Best practices for clean and efficient loops

πŸ”‘ 1. Looping Through Dictionary Keys

person = {"name": "Alice", "age": 30, "job": "Engineer"}

for key in person:
    print(key)

βœ… Explanation:

  • By default, looping through a dictionary iterates over its keys.
  • Output: name age job

βœ… Explicit .keys() (Same as Above)

for key in person.keys():
    print(key)

βœ… Note: Functionally the same, but more readable and explicit.


πŸ“¦ 2. Looping Through Dictionary Values

for value in person.values():
    print(value)

βœ… Explanation:

  • Iterates through all values: "Alice", 30, "Engineer"

πŸ” 3. Looping Through Key-Value Pairs with .items()

for key, value in person.items():
    print(f"{key}: {value}")

βœ… Explanation:

  • items() returns tuples: ("name", "Alice"), etc.
  • Tuple unpacking assigns key and value.

🧠 Real-World Example: Counting Occurrences

counts = {"apple": 3, "banana": 5, "cherry": 2}

for fruit, quantity in counts.items():
    print(f"{fruit.title()} - Quantity: {quantity}")

βœ… Explanation:

  • Practical in eCommerce, analytics, or form data parsing.

πŸ”„ Bonus: Loop Through Sorted Keys

for key in sorted(person.keys()):
    print(f"{key}: {person[key]}")

βœ… Explanation:

  • Ensures consistent order when order matters.

πŸ’‘ Best Practices

  • βœ… Use .items() when you need both keys and values.
  • βœ… Use .values() only when keys are not needed.
  • βœ… Sort keys if consistent order is required (for logs or reports).
  • ❌ Avoid modifying the dictionary while iterating.

πŸ“Œ Summary – Recap & Next Steps

Looping through a dictionary gives you full control over its contentsβ€”whether you’re filtering data, transforming values, or preparing outputs. Python’s for loop combined with dictionary view methods makes iteration clean and powerful.

πŸ” Key Takeaways:

  • βœ… Use for key in dict: or .keys() to iterate through keys.
  • βœ… Use .values() to iterate through just the values.
  • βœ… Use .items() to access both key and value in each iteration.
  • βœ… Sort keys if predictable output is needed.

βš™οΈ Real-World Relevance:
Used in API responses, form data processing, user settings, shopping carts, and configuration files.


❓ FAQ Section – Python Loop Dictionaries

❓ How do I loop through a dictionary?

βœ… Use:

for key in mydict:
    print(key)

❓ How do I loop through both key and value?

βœ… Use:

for key, value in mydict.items():
    print(key, value)

❓ Can I modify a dictionary while looping through it?

⚠️ Avoid modifying a dictionary while iterating. Use dict.copy() if needed.

❓ Is dictionary iteration ordered?

βœ… Yes, in Python 3.7+, dictionaries maintain insertion order.

❓ How do I loop through sorted dictionary keys?

βœ… Use:

for key in sorted(mydict):
    print(key, mydict[key])

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Python Dictionary: Loop Dictionaries

Or Copy Link

CONTENTS
Scroll to Top