osdir.com


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

Why no '|' operator for dict?


You can use keyword-argument unpacking in a dict-constructor.
Values of duplicate keys are overwritten from left to right. The last wins.

>>> dict1 = {'foo': 13, 'bar': 42}
>>> dict2 = {'foo': 42, 'hello': 'world'}

>>> {**dict1, **dict2}
{'bar': 42, 'foo': 42, 'hello': 'world'}

{**dict2, **dict1}
{'bar': 42, 'foo': 13, 'hello': 'world'}

You can make a Class for this task, if you need it very often:

class UDict(dict):
    def __or__(self, other):
        if not isinstance(other, (self.__class__, dict)):
            raise ValueError('Is not a dict!')
        return {**self, **other}
    __ror__ = __or__

>>> UDict({'foo': 1, 'bar': 1337}) | UDict({'bar': 43})
{'bar': 43, 'foo': 1}
>>> UDict({'foo': 1, 'bar': 1337}) | {'bar': 43}
{'bar': 43, 'foo': 1}
>>> {'foo':42} | UDict({'foo': 1, 'bar': 1337})
{'bar': 1337, 'foo': 42}


Greetings
Andre

Steven D'Aprano <steve+comp.lang.python at pearwood.info> schrieb am Mo., 5.
Feb. 2018 um 11:03 Uhr:

> On Mon, 05 Feb 2018 01:14:53 -0700, Ian Kelly wrote:
>
> > On Mon, Feb 5, 2018 at 12:35 AM, Frank Millman <frank at chagford.com>
> > wrote:
> >> So I have 2 questions -
> >>
> >> 1. Is there any particular reason why '|' is not supported?
> >
> > '|' is the set union operation, roughly equivalent to the set.union
> > method. Dicts don't have a union operation. If they did, and the same
> > key were found in both sets, what would be the value of that key in the
> > union?
>
> Obviously it should be a quantum superposition of the two values, which
> remains uncertain until such time as you actually print the value and
> observe it.
>
>
>
>
> --
> Steve
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>