使用運算子解包字典
你可以使用**
關鍵字引數解包運算子將字典中的鍵值對傳遞到函式的引數中。官方文件中的簡化示例 :
>>>
>>> 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 !
從 Python 3.5 開始,你還可以使用此語法合併任意數量的 dict
物件。
>>> 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'}
如此示例所示,重複鍵對映到其 lattermost 值(例如 Clifford
覆蓋 Nemo
)。