How to Unpacking dictionaries using the ** operator?

By Neha, 7 months ago
  • Bookmark
1

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

Unpacking
Dictionary
**operator
1 Answer
0

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"}
parrot(**d)


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

"Nemo").

Your Answer

Webinars

More webinars

Related Discussions

Running random forest algorithm with one variable

View More