How to Pass a Dictionary to a Function in Python

Passing a dictionary to a function is a common action to perform in Python programming.

This simple capability allows programmers to optimize their code and make it easier to sustain, especially when working with complex data structures like dictionaries. In this tutorial, we will guide you through the steps on how to pass a dictionary to a function in Python.

Step 1: Defining the Dictionary

First, we need to define the dictionary we want to pass to the function. Here is how you can define a dictionary in Python:

In the above sample code, we define a dictionary named animal_dict consisting of a couple of key-value pairs.

Step 2: Creating the Function

Next, let’s create a function that receives a dictionary as a parameter, loops over the dictionary, and prints each key and value to the console:

In this function, input_dict is the name of the dictionary parameter. The function utilizes a loop to traverse through all the items in the input_dict and prints each key-value pair in the dictionary.

Step 3: Passing the Dictionary to the Function

Finally, it is time to pass the dictionary to the function. Here’s how we do it:

In this case, the function print_animal_classes() is called with our previously defined dictionary animal_dict as the argument.

The Full Code

Output

dog is a canine
cat is a feline
horse is an equine

Conclusion

In this tutorial, you have learned how to pass a dictionary to a function in Python. The steps include defining a dictionary, creating a function that takes a dictionary as an argument, and finally passing the dictionary to the function.

The significance of passing data structures like a dictionary to a function can’t be overstated because it opens the door to efficient and sustainable coding practices in Python.