fir3net
PPS-Firenetbanner-780.5x190-30-03-17

Python - Packing and Unpacking Dictionaries

Today I will explain the concept of unpacking and packing within Python.

Unpacking

Unpacking allows us to pass keyword arguments (i.e dictionary) to a function via the use of the ** syntax. We can then access the values within the function like so,

>>> def do_something(**kwargs):
...     print kwargs['a']
...     print kwargs['b']
...     print kwargs['c']

Packing

Packing allows you to pass a set of keyword values to a function, i.e like a dictionary. This is far quicker then having to explicitly pass each keyword. An example is shown below,

// with packing
>>> some_values = {'b': 2, 'c': 3}
>>> do_something(a=1, **some_values)
1
2
3

// without packing.
>> do_something(a=1, b=2, c=3)
1
2
3

Tags: Python

About the Author

RDonato

R Donato

Rick Donato is the Founder and Chief Editor of Fir3net.com. He currently works as a Principal Network Security Engineer and has a keen interest in automation and the cloud.

You can find Rick on Twitter @f3lix001