Set Operations on Dicts

Marco Kaulea marco.kaulea at gmail.com
Mon Feb 8 07:33:56 EST 2016


On Mon, Feb 8, 2016 at 1:17 PM, Jussi Piitulainen <
jussi.piitulainen at helsinki.fi> wrote:

> 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.
>
I don't expect this to be really useful. I only thought about using a set
as a second argument.


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:
>
That is the restriction I had in mind.

{ 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
>
> That is basically what I did. But I expect this could be quite slow, since
it has to take
each value in s and perform a lookup in d. I would expect the pure set
implementation
to be more optimized.


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() }

This seems like it might be useful for default configurations, as that is
currently
quite the hassle to do with `x = conf.get('x', fallback="default")



More information about the Python-list mailing list