使用运算符解包字典

你可以使用**关键字参数解包运算符将字典中的键值对传递到函数的参数中。官方文档中的简化示例 :

>>>
>>> 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)。