1

Python has the ** operator, which spreads a dictionary within another dictionary or function arguments. This works well in the example:

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

However, if one of the value is a dictionary itself, it is overwritten completetly.

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

It is overwritten completely. For now I'll make a function that unpacks them recursively, but i was wondering if there is an actual way to do this within python (not necessarily a syntax feature, a standard library function would be OK as well).

If there is no such feature, that is also an acceptable answer.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
DownloadPizza
  • 3,307
  • 1
  • 12
  • 27

1 Answers1

0

This issue is less about the spread operator (which just expands a dictionary), and more about how the new dictionary is being constructed.

From the 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.

This is apparent from the first example you gave, where the value of a:5 is overwritten with a:15, rather than being summed to a:20.

The same thing is happening with the dictionaries: the previous values are being overwritten rather than added togather, so if you want the previous values to be concatenated you will need to define that operation manually.

Luke Storry
  • 6,032
  • 1
  • 9
  • 22