Given a dictionary, the task is to iterate through its elements. Depending on the requirement, we can iterate over the keys, values, or both key-value pairs. For Example:
Input: d = {"name": "Kate", "age": 25}
Output:
name Kate
age 25
Now, let's explore different methods to iterate over a dictionary in Python.
Using items()
items() method returns both the key and its corresponding value together. This is useful when both pieces of information are needed during iteration.
d = {"name": "Emma", "age": 25, "city": "NY"}
for k, v in d.items():
print(k, v)
Output
name Emma age 25 city NY
Explanation: items() returns each dictionary entry as a (key, value) pair, which is unpacked into k and v during every iteration.
Using keys()
keys() method returns all the keys of the dictionary. It is useful when you only need to work with the keys or access values later using those keys.
d = {"name": "David", "age": 25, "city": "NY"}
for k in d.keys():
print(k)
Output
name age city
Explanation: loop iterates over each key returned by keys() and prints it one by one.
Using values()
values() method returns all the values stored in the dictionary without exposing the corresponding keys.
d = {"name": "Harry", "age": 25, "city": "NY"}
for v in d.values():
print(v)
Output
Harry 25 NY
Explanation: values() returns all dictionary values, which are accessed one at a time during the loop.
Using Dictionary Directly
A dictionary itself is iterable. Iterating over it directly returns its keys, which can then be used to access the corresponding values.
d = {"name": "Jake", "age": 25, "city": "NY"}
for k in d:
print(k, d[k])
Output
name Jake age 25 city NY
Explanation: When a dictionary is used directly in a for loop, each iteration returns a key. The corresponding value is then accessed using d[k].