Python | Passing dictionary as keyword arguments

Python | Passing dictionary as keyword arguments

In Python, you can use the ** unpacking operator to pass a dictionary as keyword arguments to a function. This technique can be especially useful when working with functions that accept a variable number of keyword arguments.

Here's how you can do it:

Example:

  • Define a function that takes some keyword arguments:
def display_data(name, age): print(f"Name: {name}") print(f"Age: {age}") 
  • Create a dictionary with keys corresponding to the names of the function's parameters:
person_data = { "name": "Alice", "age": 30 } 
  • Pass the dictionary as keyword arguments using the ** unpacking operator:
display_data(**person_data) 

Output:

Name: Alice Age: 30 

Variable Number of Keyword Arguments:

You can also use this technique with functions that accept a variable number of keyword arguments using **kwargs:

def display_data_v2(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") 

Now, you can pass any dictionary, regardless of its size:

person_data_v2 = { "name": "Bob", "age": 25, "job": "Engineer", "city": "New York" } display_data_v2(**person_data_v2) 

Output:

name: Bob age: 25 job: Engineer city: New York 

This method of passing a dictionary as keyword arguments can simplify the dynamic generation and passing of arguments to functions, making the code more flexible and readable.


More Tags

android-tabs retrofit gantt-chart digital-persona-sdk moq spotify asp.net-mvc-5.1 v-model python-tesseract variable-names

More Programming Guides

Other Guides

More Programming Examples