All Courses

How to Unpacking dictionaries using the ** operator?

By Neha, 2 years ago
  • Bookmark

How to use ** keyword for unpacking dictionary in python ?

1 Answer

You can use the ** keyword argument unpacking operator to deliver the key-value pairs in a dictionary into a

function's arguments.

def parrot(voltage, state, action):
    print("This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.", end=' ')
    print("E's", state, "!")

d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}

This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

As of Python 3.5 you can also use this syntax to merge an arbitrary number of dict objects.

>>> fish = {'name': "Nemo", 'hands': "fins", 'special': "gills"}
>>> dog = {'name': "Clifford", 'hands': "paws", 'color': "red"}
>>> fishdog = {**fish, **dog}
>>> fishdog
{'hands': 'paws', 'color': 'red', 'name': 'Clifford', 'special': 'gills'}

As this example demonstrates, duplicate keys map to their lattermost value (for example "Clifford" overrides


Your Answer


More webinars

Related Discussions

Running random forest algorithm with one variable

View More