Iterating Dictionaries
π¨π Technique Card: Iterating Dictionaries (practical)
Basic Iteration (looping)
We can iterate over key:value pairs in Python dictionaries using:
my_dict = {"bobo": "blue", "lisa": "silver", "dianne": "green"}
for key in my_dict:
print(f"{key} loves {my_dict[key]}")
π§ What About .items()
The .items()
method in Python lets you work with both the key and the value of a dictionary at the same time. It gives you a dict_items
object β think of it like a bag of key-value pairs!
π§ͺ How It Works
my_dict = {"apple": 1, "banana": 2}
# Looping with .items()
for key, value in my_dict.items():
print(key, value)
π This is a quick and clear way to get both the name (key) and the number (value).
Note
We often just use k, v
instead of key, value
π What You Might See
print(my_dict.items())
# Output: dict_items([('apple', 1), ('banana', 2)])
It might look strange, but itβs just a collection of pairs!
π οΈ You Can Also
β Turn It Into a List
list_of_pairs = list(my_dict.items())
print(list_of_pairs)
# [('apple', 1), ('banana', 2)]
π― Challenges to Try
- Create a dictionary of animals and how many of each you saw.
- Use
.items()
to print a sentence like:"I saw 3 foxes."
- Convert your dictionary to a list of key-value pairs.