您可以使用**关键字参数解包运算符将字典中的键/值对传递到函数的参数中。官方文档中的一个简化示例:
>>> >>> def parrot(voltage, state, action): ... print("This parrot wouldn't", action, end=' ') ... print("if you put", voltage, "伏特通过它。", 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 伏特通过它。 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'}
如本示例所示,重复的键映射到它们的最后一个值(例如,“ Clifford”覆盖“ Nemo”)。