osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Why no '|' operator for dict?


2018-02-05 9:14 GMT+01:00 Ian Kelly <ian.g.kelly at gmail.com>:
> On Mon, Feb 5, 2018 at 12:35 AM, Frank Millman <frank at chagford.com> wrote:
>> 2. Is there a better way to do what I want?
>
> The dict.items() view is explicitly set-like and can be unioned, so
> you can do this:
>
> py> dict(d1.items() | d2.items())
>
> As to the question of which value will appear in the union in the case
> of duplicate keys, it will be whichever one arbitrarily appears later
> in the iteration order of the intermediate set.

Since Python 3.5, it is also possible to use PEP448 generalized unpacking:

dict([*d1.items(), *d2.items()])

In which case the value that appears in case of duplicate keys is
better defined, it will be the one appearing in the last dictionnary.