How To Print A Dictionary Vertically Python

In this tutorial, you will learn how to print the elements of a dictionary vertically using Python. This method is useful for displaying dictionary contents in a more organized and readable format.

First, let’s give a brief overview of what a dictionary is. A dictionary is a mutable and unordered collection of key-value pairs. Each key in the dictionary must be unique and can be any hashable data type, such as integers, strings, and tuples. The values can be any data type including numbers, strings, and even other dictionaries.

Let’s dive into the steps required to achieve printing a dictionary vertically using Python.

Step 1: Create a dictionary

Let’s begin by creating a dictionary that we will use for this tutorial. You can create your own dictionary or use the sample dictionary provided below.

sample_dictionary = {
    "Name": "John",
    "Age": 30,
    "Country": "USA",
    "City": "New York",
}

Here, we have a dictionary with four key-value pairs.

Step 2: Writing a function to print the dictionary vertically

Now, let’s write a Python function called print_dictionary_vertically() that takes a dictionary as an argument, iterates through its key-value pairs, and prints the keys and values vertically.

def print_dictionary_vertically(dictionary):
    for key, value in dictionary.items():
        print(f"{key}: {value}")

This function uses the items() method to loop through and access the key-value pairs of the dictionary. The print() statement inside the loop prints the key and value on separate lines. The f-string is used for string formatting.

Step 3: Call the function and pass the dictionary

Once the function is written, you can call it and pass the sample dictionary as an argument.

The output of the code:

Name: John
Age: 30
Country: USA
City: New York

Full Code

Here’s the full code we used in this tutorial:

Conclusion

In this tutorial, you have learned how to print a dictionary vertically in Python. This can help improve the visual representation of complex data structures and make the data more accessible and easy to understand. By following these simple steps, you can easily print dictionaries vertically in Python.