Set Operations on Dicts

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Mon Feb 8 07:17:36 EST 2016


Marco Kaulea writes:

> In one talk (I think it was [1]) it was described that sets are
> basically dicts without the values.  Therefor it should be easy to
> apply set operations on dicts, for example:
>
> {'a': 123, 'b': 456} & {'a'} => {'a': 123}
> {'a': 123, 'b': 456} - {'a'} => {'b': 456}
>
> This if currently not implemented. Is there a technical reason that
> this is difficult or are there a lot of corner cases that make it not
> worth the trouble?

I think nobody was quite willing to lay down the law on which dictionary
would take precedence when they have keys in common but different values
on those keys. Both ways make sense, and sometimes you want something
like arithmetic done to combine the values on common keys.

(A collection.Counter does some version of the latter, I think. Maybe
the answer is to create a custom class that allows what you want?)

But that's an interesting proposal to only allow sets as the second
argument. Those particular cases may not be *too* difficult to express
as comprehensions, though still quite a mouthful compared to your
suggestion:

{ k:d[k] for k in d if k in s }     # d & s

{ k:d[k] for k in d if k not in s } # d - s

Perhaps there is already some more compact expression for these?

Also, what would be the nicest current way to express a priority union
of dicts?

{ k:(d if k in d else e)[k] for k in d.keys() | e.keys() }

> I have not spend a lot of time on this, I just needed a feature like
> that and was surprised that it did not exists.
>
> - Marco
>
> [1] https://www.youtube.com/watch?v=C4Kc8xzcA68


More information about the Python-list mailing list