Google News
logo
Python Program to Loop through both keys an values, by using the items() function
In the following example of Python program to loop through both keys and values of a dictionary using the `items()` function :
Program :
my_dict = {"apple": 2, "banana": 3, "orange": 1}

for key, value in my_dict.items():
    print(key, value)
Output :
apple 2
banana 3
orange 1
In the above program, we first define a dictionary `my_dict` with some key-value pairs. We then use a `for` loop to iterate through the items of the dictionary using the `items()` function.

The `items()` function returns a list of key-value pairs as tuples, which we can unpack into separate variables `key` and `value`. Finally, we print out the key and value of each item using the `print()` function.