How to Print All Key-Value Pairs in a Dictionary in Python?

Estimated read time 1 min read

To print all key-value pairs in a dictionary in Python, you can use a for loop to iterate through the keys of the dictionary, and then use the keys to access the corresponding values. Here’s an example:

my_dict = {"apple": 2, "banana": 3, "orange": 1}

for key in my_dict:
    print(key, "-", my_dict[key])

In this example, we have a dictionary called my_dict with three key-value pairs. To print all of the key-value pairs, we use a for loop to iterate through the keys of the dictionary ("apple", "banana", and "orange").

Inside the loop, we use the key to access the corresponding value in the dictionary (my_dict[key]), and then print both the key and value to the console using the print() function.

The output of this code would be:

apple - 2
banana - 3
orange - 1

Note that the order of the key-value pairs may not be the same as the order in which they were added to the dictionary, as dictionaries in Python are unordered. If you need to preserve the order of the key-value pairs, you can use a collections.OrderedDict instead of a regular dictionary.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply