World's Best AI Learning Platform with profoundly Demanding Certification Programs
Designed by IITian's, only for AI Learners.
How to use ** keyword for unpacking dictionary in python ?
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").