Passing a Dictionary as Arguments to a Function in Python


Python is a powerful and versatile programming language that provides a wide range of data structures to handle complex data. They offer a flexible and efficient way to organize and manipulate information, making them a popular choice for various programming tasks. This capability is especially useful when dealing with complex data structures or when you need to pass multiple related values to a function without explicitly defining numerous individual parameters.

Accessing Dictionary Values within a Function

Once the dictionary is passed as an argument, you can access its values using the keys within the function. This allows you to retrieve specific data or perform operations based on the dictionary's content.

To access dictionary values within a function, you can use the familiar square bracket notation ([]) along with the corresponding key. Let's look at an example −

Example

def print_name_age(person):
   print(f"Name: {person['name']}")
   print(f"Age: {person['age']}")

person_info = {'name': 'John Doe', 'age': 25}
print_name_age(person_info)

In the above code, we define a function called print_name_age that takes a dictionary person as an argument. Within the function, we access the values using the respective keys ('name' and 'age') and print them.

When we call the function and pass the person_info dictionary, it retrieves the values associated with the keys 'name' and 'age' and displays them 

Output

Name: John Doe
Age: 25

By accessing dictionary values within a function, you can perform various operations such as printing, manipulating, or using them in calculations, providing you with the flexibility to work with dynamic data.

Modifying Dictionary Values within a Function

In Python, dictionaries are mutable objects, meaning their values can be modified. When a dictionary is passed as an argument to a function, you can directly modify its values within the function, and the changes will persist outside the function scope.

Example

Let's take a look at an example to understand how to modify dictionary values within a function 

def increment_age(person):
   person['age'] += 1

person_info = {'name': 'John Doe', 'age': 25}
print(f"Original age: {person_info['age']}")
increment_age(person_info)
print(f"New age: {person_info['age']}")

In the code snippet above, we define a function called increment_age that takes a dictionary person as an argument. Within the function, we access the 'age' key of the dictionary and increment its value by 1.

When we call the increment_age function and pass the person_info dictionary, it modifies the value of 'age' within the dictionary. The output of the above code will be:

Output

Original age: 25
New age: 26

As you can see, the original value of 'age' in the person_info dictionary is modified from 25 to 26 within the increment_age function.

Iterating Over a Dictionary within a Function

Iterating over a dictionary allows you to access and operate on each key-value pair within the dictionary. This is particularly useful when you need to perform certain actions or computations on all the items in the dictionary.

To iterate over a dictionary within a function, you can use a loop along with the items() method, which returns a view object containing the key-value pairs of the dictionary.

Example

Let's consider an example 

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

person_info = {'name': 'John Doe', 'age': 25, 'country': 'USA'}
print_dict_items(person_info)

In the code above, we define a function called print_dict_items that takes a dictionary dictionary as an argument. Within the function, we iterate over the items of the dictionary using the items() method. For each iteration, we unpack the key-value pair into the variables key and value and print them.

When we call the print_dict_items function and pass the person_info dictionary, it iterates over the dictionary's items and prints each key-value pair 

Output

Key: name, Value: John Doe
Key: age, Value: 25
Key: country, Value: USA

By iterating over a dictionary within a function, you can perform various operations on each key-value pair, such as performing calculations, filtering data, or applying specific logic.

Passing a Dictionary as Keyword Arguments

Python provides a convenient way to pass a dictionary as keyword arguments to a function. This allows you to use the dictionary's keys as argument names and their corresponding values as argument values when calling the function. This technique simplifies the process of passing multiple arguments and provides a clean and readable syntax.

To pass a dictionary as keyword arguments, you can use the double asterisk (**) notation before the dictionary name. Let's see an example to understand how it works −

Example

def print_person_details(name, age, country):
    print(f"Name: {name}")
    print(f"Age: {age}")
    print(f"Country: {country}")

person_info = {'name': 'John Doe', 'age': 25, 'country': 'USA'}
print_person_details(**person_info)

In the code above, we define a function called print_person_details that expects three arguments: name, age, and country. When we call the function, instead of passing the arguments individually, we pass the person_info dictionary using the double asterisk notation (**).

The dictionary's keys ('name', 'age', and 'country') match the function's argument names, and the corresponding values are assigned to those arguments. As a result, the function prints the person's details based on the dictionary values 

Output

Name: John Doe
Age: 25
Country: USA

This approach is particularly useful when you have a large number of arguments or when the argument list is subject to change. However, it's important to note that the dictionary's keys must match the argument names in the function. Otherwise, you may encounter a TypeError or unexpected behavior.

Using Unpacking to Pass Dictionary Items as Function Arguments

In addition to passing the entire dictionary or using it as keyword arguments, you can also unpack specific items from the dictionary and pass them as individual arguments to a function. This technique provides granular control over which dictionary items are used as function arguments.

To unpack specific dictionary items, you can use the asterisk (*) notation before the dictionary name. Let's take a look at an example 

Example

def print_name_age(name, age):
   print(f"Name: {name}")
   print(f"Age: {age}")

person_info = {'name': 'John Doe', 'age': 25, 'country': 'USA'}
print_name_age(**person_info)

In the code above, we define a function called print_name_age that expects two arguments: name and age. When we call the function, we pass the person_info dictionary using the double asterisk notation (**).

The dictionary contains the keys 'name', 'age', and 'country'. However, since we only want to unpack 'name' and 'age', only those items are used as arguments when calling the function. The dictionary's 'country' key is ignored in this case.

As a result, the function prints the person's name and age based on the corresponding dictionary values −

Output

Name: John Doe
Age: 25

It's worth noting that the keys you want to unpack must exist in the dictionary; otherwise, a TypeError will be raised.

Conclusion

In Python, dictionaries are powerful data structures that allow you to store and manipulate data in key-value pairs. Passing dictionaries as arguments to functions enhances the flexibility and adaptability of your code, enabling you to work with dynamic data and complex data structures more effectively.

Updated on: 14-Aug-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements