How to loop through all key-value pairs in a dictionary?
Published on Aug. 22, 2023, 12:17 p.m.
To loop through all key-value pairs in a Python dictionary, you can use the items()
method. Here is an example of how to iterate over all the key-value pairs in a dictionary using the items()
method:
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
for key, value in my_dict.items():
print(key, value)
This will output:
key1 value1
key2 value2
key3 value3
In this example, items()
returns a list of tuples, where each tuple contains a key-value pair from the dictionary. The for
loop iterates over the tuples and unpacks each tuple into two variables, key
and value
, which you can use to access the key and value for each iteration.