Python: Passing Dictionary as Arguments to Function

Python: Passing Dictionary as Arguments to Function

In Python, you can pass a dictionary to a function by unpacking its key-value pairs into arguments using the ** operator. This is especially useful when the dictionary keys match the function's parameter names.

Here's an example to illustrate this:

  1. Passing dictionary as arguments

    def greet(name, age): print(f"Hello {name}, you are {age} years old.") person_info = {"name": "John", "age": 30} greet(**person_info) 

    Output:

    Hello John, you are 30 years old. 
  2. Using dictionary unpacking with functions having variable keyword arguments (**kwargs)

    If you're unsure of what keyword arguments may be passed or if you want to handle any extra keys in the dictionary, you can use **kwargs in the function definition:

    def display_data(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") data = { "name": "Alice", "age": 25, "city": "New York" } display_data(**data) 

    Output:

    name: Alice age: 25 city: New York 

Remember that you can only use the ** unpacking method with dictionaries. It won't work with other iterable types like lists or tuples. Similarly, you would use * to unpack elements from sequences like lists or tuples into positional arguments.


More Tags

r-factor tempus-dominus-datetimepicker svg yii-extensions google-docs-api microsoft-metro android-mediascanner benchmarking variable-names popup

More Programming Guides

Other Guides

More Programming Examples