Python 嵌套字典传播 (**kwargs)

Python nested dictionary spread (**kwargs)

Python 有 ** 运算符,它在另一个字典或函数参数中传播一个字典。 这在示例中效果很好:

default = {'a':5}
a = {'a':15}
{**default, **a}
// => {'a': 15}

但是,如果值之一是字典本身,它将被完全覆盖。

default = {'a': {'aa' : 10, 'ab' : 15}}
a = {'a': {'aa': 15}}
{**default, **a}
// => {'a': {'aa': 15}}
// expected => {'a': {'aa' : 15, 'ab' : 15}}

完全覆盖。现在我将创建一个递归解压它们的函数,但我想知道是否有在 python 中执行此操作的实际方法(不一定是语法功能,标准库函数也可以)。

如果没有这个功能,那也是可以接受的答案。

这个问题不是关于扩展运算符(它只是扩展字典),而是关于如何构建新字典。

来自dict docs:

If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.

If a key being added is already present, the value from the keyword argument replaces the value from the positional argument.

从您给出的第一个示例中可以看出这一点,其中 a:5 的值被 a:15 覆盖,而不是求和为 a:20

字典也发生了同样的事情:以前的值被覆盖而不是添加到一起,所以如果你想连接以前的值,你需要手动定义该操作。