Sling Academy
Home/Python/Python: Passing a dictionary as a function argument

Python: Passing a dictionary as a function argument

Last updated: February 12, 2024

Overview

In Python, dictionaries are versatile containers that can hold multiple data types as key-value pairs, making them an essential tool for developers. This article explores how to pass dictionaries as arguments to functions, ranging from basic to advanced examples, to harness the full potential of this powerful feature.

Understanding Dictionaries in Python

Before diving into how to pass dictionaries as function arguments, let’s briefly revisit what dictionaries are. A dictionary in Python is a collection that is unordered, changeable, and indexed. Dictionaries are written with curly brackets, and they have keys and values.

example_dict = {"name": "John", "age": 30}
print(example_dict['name'])  # Output: John

Basic Example: Passing a Simple Dictionary as an Argument

To begin, let’s see a simple example of passing a dictionary as an argument to a function. This function accepts a dictionary and prints the values associated with a specified key.

def print_value(my_dict, key):
    if key in my_dict:
        print(my_dict[key])
    else:
        print("Key not found.")

my_info = {"name": "Alice", "age": 25}
print_value(my_info, 'name')  # Output: Alice

Intermediate Example: Function Modifying a Dictionary

Moving to an intermediate level, this function not only accepts a dictionary as an argument but also modifies it by adding a new key-value pair.

def modify_dict(my_dict, key, value):
    my_dict[key] = value
    print("Updated dictionary:", my_dict)

sample_dict = {"country": "USA", "state": "California"}
modify_dict(sample_dict, "city", "San Francisco")  # Updated dictionary: {'country': 'USA', 'state': 'California', 'city': 'San Francisco'}

Advanced Example: Using **kwargs in Functions

For a more advanced approach, Python offers the **kwargs syntax to pass an arbitrary number of keyword arguments (in the form of a dictionary) to functions. This technique can greatly simplify your code when dealing with multiple keyword arguments.

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

greet_user(name="Emily", profession="Engineer") # Output:
# Name: Emily
# Profession: Engineer

Manipulating Dictionaries with Functions

Besides simply passing dictionaries as arguments, functions can perform complex manipulations on them. This includes merging dictionaries, filtering contents, and more sophisticated data manipulation techniques.

def merge_dicts(dict1, dict2):
    merged_dict = {**dict1, **dict2}
    return merged_dict

first_dict = {"fruit": "Apple", "vegetable": "Carrot"}
second_dict = {"drink": "Water", "dessert": "Cake"}
result = merge_dicts(first_dict, second_dict)
print(result)  # {'fruit': 'Apple', 'vegetable': 'Carrot', 'drink': 'Water', 'dessert': 'Cake'}

Utilizing Dictionaries for Dynamic Argument Passing

Dictionaries can also serve as a powerful tool for dynamically passing arguments to functions. This capability allows developers to build more flexible and scalable applications.

def dynamic_arguments_function(**kwargs):
    for argument, value in kwargs.items():
        print(f"Argument: {argument}, Value: {value}")

dynamic_arguments_function(temperature=72, humidity=60, wind_speed=15)  # Output:
# Argument: temperature, Value: 72
# Argument: humidity, Value: 60
# Argument: wind_speed, Value: 15

Conclusion

As we’ve explored, passing dictionaries as function arguments in Python can streamline your code and enhance flexibility. From simple print functions to dynamic argument passing with **kwargs, mastering this technique opens up a world of possibility for efficient coding and complex data manipulation. Whether you’re a beginner or an advanced programmer, understanding how to effectively use dictionaries in functions is a valuable skill in any Python developer’s arsenal.

Next Article: Python: How to find the difference between 2 dictionaries

Previous Article: Python: How to get the first/last item from a dictionary

Series: Working with Dict, Set, and Tuple in Python

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots