Introduction
Python passes dictionary to function – Dictionaries are mutable. So if you change a dictionary inside a function, the change will reflect in the outer scope as well. You can pass a dictionary to a function as an argument.
function(dictionary)
What is a dictionary?
In Python, a dictionary is an unordered collection of items. Each item in a dictionary has a key/value pair. The key is used to access the value.
A dictionary can be created using the dict()
function. Alternatively, you can create a dictionary using curly braces {}
.
Dictionaries are mutable, which means they can be changed. You can add new items or remove existing items. You can also change the value of an existing item.
What is a function?
In Python, a function is a group of related statements that perform a specific task.
Functions help us to organize our code, making it easier to read and write. They also allow us to reuse code: once we have written and debugged a function, we can use it over and over again without having to write new code.
A function is like a recipe: it takes some input (the ingredients), does something with them (the steps), and produces some output (the result). The input and output can be anything: numbers, strings, lists, dictionaries, other functions, etc.
How to pass a dictionary to a function?
A function can take dictionary asargument. When a dictionary is passed to a function, the function receives a reference to the dictionary. It doesn’t copy the dictionary. Any changes that you make to the dictionary in the function will be reflected in the caller’s namespace.
Here is an example:
def Average(lst):
return sum(lst) / len(lst)
Driver code
print(Average({‘A’: 10, ‘B’: 20, ‘C’: 30}))
Conclusion
Although the above methods are the most common ways to pass a dictionary to a function, there are other ways as well. You can use the ** operator, unpacking, or you can pass the dictionary in as a keyword argument.