Chapter 10 Dictionaries

10.5 Dicts and Functions

Similar to lists, dicts are mutable. As a result, dict arguments can be modified by a function. The function filterdict below takes a simple dict argument, and changes all the items with 0 value to 10.

We have introduced the use of a special list parameter, marked with *, to support an arbitrary number of optional argument. Python additionally allows the use of a special dict parameter, marked with **, to support an arbitrary number of keyword arguments in function calls. When a special argument with ** is given in the definition of a function, all keyword arguments that cannot be explicitly matched in a call to the function are packed into a dict and assigned to the special parameter, with the keys being the string form of the keywords, and the corresponding values being the values of the input arguments.

For example,

In the example above, the function f takes two explicit arguments a and b, and a special dict argument d, printing out all the explicitly and implicitly matched arguments and their values. The outputs show that the arguments a and b are always matched explicitly, while any additional keyword arguments are packed into d.

The special dict argument and the special list argument can be used simultaneously, accepting keyword arguments and non-keyword arguments that cannot be explicitly matched, respectively.

Similar to the case of lists, a dict can be passed as keyword arguments to function by using the prefix **.

In the example above, a call to f(∗∗d) is effectively the same as a call to f(a = 1, b = 2).

© Copyright 2024 GS Ng.

Next Section - 10.6 Copying Dicts