In Python, a dict (dictionary) stores data as key-value pairs. Looping through dictionaries lets you read or process:
for key in dict → iterates over keys (default behavior).dict.keys() → explicit view of all keys.dict.values() → view of all values.dict.items() → view of (key, value) pairs.When you loop directly over a dictionary, Python gives you each key. You can then use the key to access its value.
for key in my_dict: is equivalent to for key in my_dict.keys():
Use values() when you only care about the data, not the key names.
Use items() to get both key and value at the same time. Each iteration returns a tuple (key, value) which you can unpack.
By default, looping through a dictionary iterates over its keys.
person = {"name": "Alice", "age": 25, "city": "New York"}
for key in person:
print(key, "->", person[key])
# Output:
# name -> Alice
# age -> 25
# city -> New York
Use values() to loop through only the values in the dictionary.
for value in person.values():
print(value)
# Output:
# Alice
# 25
# New York
Use items() to loop through both keys and values at the same time.
for key, value in person.items():
print(f"{key} -> {value}")
# Output:
# name -> Alice
# age -> 25
# city -> New York
For the keys loop, each iteration gives a key like "name", which is then used as person[key] to access its value (e.g., "Alice").
For the values loop, person.values() returns all stored values, so the loop directly prints "Alice", 25, and "New York".
For the items loop, person.items() returns pairs like ("name", "Alice"). In each iteration, key receives the first element and value receives the second element, which we format as key -> value.
items() when you need both keys and values simultaneously.values() if you do not need the keys at all.list(dict.keys()) copy instead of the original view.person dictionary and:
key -> value.items() to print: "Alice lives in New York" using the dictionary data.