43. Unpacking Keyword Arguments (kwargs)

def func(val1=3, val2=4, val3=6):
    return val1 + val2 + val3

values = {"val2":91, "val3":-101}
print(func(**values))

Programming is about using lower-level functionality to create higher-level functionality. In general, any programming language is a collection of functions that in turn build upon functions provided by the operating system. You must master the art of building your own code with the help of existing functionality. Do not reinvent the wheel!


Functions are generic code snippets that can be tailored to your needs via keyword arguments.

The puzzle shows a function that calculates the sum of three keyword arguments. The keyword arguments are initialized with a default value in case they are not defined by the function caller.

The puzzle introduces two concepts: dictionaries and unpacking keyword arguments.


1) Dictionaries are Python data structures, defined via the bracket notation {}, that store key-value pairs. Python dictionaries work like real-world dictionaries: the keys are the words and the values are the explanations. You access the explanation to a given word via the index table. Similarly, in a Python dictionary, you access the values using the method of indexing. The indices (or keys) can be strings, integers, or any other immutable data type.


2) An interesting twist in the puzzle is to deliver keyword arguments via a dictionary using the **-operator. The **-operator unpacks the key-value pairs in the dictionary and matches those with the keyword arguments. As the first keyword argument val1 is not declared in the dictionary, it is initialized to its default value.

Complete and Continue  
Discussion

3 comments