[Python-ideas] Allow using ** twice

Steven D'Aprano steve at pearwood.info
Fri Jun 7 02:06:57 CEST 2013


On 07/06/13 00:54, Markus Unterwaditzer wrote:
> This indicates for me that it generally should be possible to generate the union of two dicts with sth like {} + {}.

What is the union of two dicts? Given:

a = {'a':1, 'b':2, 'c':3}
b = {'b':20, 'c':30, 'd':40}

the union a+b could be any of:

{'a':1, 'b':2, 'c':3, 'd':40}
{'a':1, 'b':20, 'c':30, 'd':40}
{'a':1, 'b':22, 'c':33, 'd':40}
raise an exception due to duplicate keys

and I am sure that there are use-cases for all four, or more, strategies.

Since all of these can be easily done with a small helper function, that is probably the best way to do this. E.g. to implement the first behaviour:

def merge(*dicts):
     D = {}
     for d in reversed(dicts):
         D.update(d)
     return D


and then:

spam(**merge(a, b))


solves the O.P.'s problem nicely.

So I am -1 on both the original suggestion spam(**a, **b) and any particular union or merge operator for dicts.



-- 
Steven


More information about the Python-ideas mailing list