Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Passing a Dictionary as Arguments to a Function in Python
Dictionaries in Python are powerful data structures that store key-value pairs. You can pass them as arguments to functions in several ways, making your code more flexible and efficient when working with structured data.
Basic Dictionary as Function Argument
The simplest way is to pass a dictionary directly as a parameter ?
def print_person_info(person):
print(f"Name: {person['name']}")
print(f"Age: {person['age']}")
person_data = {'name': 'Alice', 'age': 30}
print_person_info(person_data)
Name: Alice Age: 30
Modifying Dictionary Values in Functions
Since dictionaries are mutable, changes made inside the function affect the original dictionary ?
def update_age(person):
person['age'] += 1
return person
person_data = {'name': 'Bob', 'age': 25}
print(f"Before: {person_data}")
update_age(person_data)
print(f"After: {person_data}")
Before: {'name': 'Bob', 'age': 25}
After: {'name': 'Bob', 'age': 26}
Using ** to Pass Dictionary as Keyword Arguments
The double asterisk operator unpacks dictionary keys as parameter names ?
def create_profile(name, age, city):
return f"{name} is {age} years old and lives in {city}"
user_info = {'name': 'Carol', 'age': 28, 'city': 'New York'}
profile = create_profile(**user_info)
print(profile)
Carol is 28 years old and lives in New York
Iterating Over Dictionary in Functions
You can loop through dictionary items to process all key-value pairs ?
def display_all_info(data):
for key, value in data.items():
print(f"{key.title()}: {value}")
student = {'name': 'David', 'grade': 'A', 'subject': 'Math'}
display_all_info(student)
Name: David Grade: A Subject: Math
Handling Missing Keys Safely
Use the get() method to avoid KeyError when accessing dictionary values ?
def safe_print_info(person):
name = person.get('name', 'Unknown')
age = person.get('age', 'Not specified')
print(f"Name: {name}, Age: {age}")
incomplete_data = {'name': 'Eve'}
safe_print_info(incomplete_data)
Name: Eve, Age: Not specified
Comparison of Methods
| Method | Use Case | Syntax |
|---|---|---|
| Direct passing | Access via keys inside function | func(dictionary) |
| Keyword unpacking | Keys match parameter names | func(**dictionary) |
| Safe access | Handle missing keys gracefully | dict.get(key, default) |
Conclusion
Passing dictionaries to functions provides flexibility in handling structured data. Use direct passing for key-based access, ** unpacking when keys match parameters, and get() for safe key access.
